🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: add custom-query backend (#6006)
Steffen Schmitz0897ac753b79
diff --git a/packages/shared/src/server/clickhouse/schema.ts b/packages/shared/src/server/clickhouse/schema.tsindex 37d8e6c842..2f3715da6e 100644--- a/packages/shared/src/server/clickhouse/schema.ts+++ b/packages/shared/src/server/clickhouse/schema.ts@@ -2,6 +2,11 @@ export const ClickhouseTableNames = {traces: "traces",observations: "observations",scores: "scores",++ // Virtual tables for dashboards+ // TODO: Check if we can do this more elegantly+ scores_numeric: "scores_numeric",+ scores_categorical: "scores_categorical",} as const;export type ClickhouseTableName = keyof typeof ClickhouseTableNames;diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex c03336c2d5..6a1f220f09 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -18,3 +18,4 @@ export {type ClickhouseOperator,} from "./clickhouse-sql/clickhouse-filter";export { orderByToClickhouseSql } from "./clickhouse-sql/orderby-factory";+export { createFilterFromFilterState } from "./clickhouse-sql/factory";diff --git a/packages/shared/src/tableDefinitions/mapDashboards.ts b/packages/shared/src/tableDefinitions/mapDashboards.tsindex c997f48bfc..ec85afabac 100644--- a/packages/shared/src/tableDefinitions/mapDashboards.ts+++ b/packages/shared/src/tableDefinitions/mapDashboards.ts@@ -1,5 +1,7 @@import { UiColumnMappings } from "./types";+// Make sure to update web/src/features/query/dashboardUiTableToViewMapping.ts if you make changes+export const dashboardColumnDefinitions: UiColumnMappings = [{uiTableName: "Trace Name",diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.tsnew file mode 100644index 0000000000..33d80e5b7c--- /dev/null+++ b/web/src/__tests__/queryBuilder.servertest.ts@@ -0,0 +1,2445 @@+import { clickhouseClient } from "@langfuse/shared/src/server";+import { QueryBuilder } from "@/src/features/query/server/queryBuilder";+import { type QueryType } from "@/src/features/query/types";+import {+ createTrace,+ createObservation,+ createTracesCh,+ createObservationsCh,+ createScore,+ createScoresCh,+} from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";++describe("queryBuilder", () => {+ describe("query builder creates executable SQL", () => {+ it.each([+ [+ "simple trace query",+ {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "count", aggregation: "count" },+ { measure: "observationsCount", aggregation: "p95" },+ ],+ filters: [+ {+ column: "name",+ operator: "=",+ value: "qa",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ } as QueryType,+ ],+ [+ "query with auto time dimension for month granularity",+ {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: {+ granularity: "auto",+ },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z", // 2 months difference+ orderBy: null,+ } as QueryType,+ ],+ [+ "query with specific time dimension granularity",+ {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: {+ granularity: "day",+ },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-01-10T00:00:00.000Z", // 10 days difference+ orderBy: null,+ } as QueryType,+ ],+ [+ "trace query without dimensions",+ {+ view: "traces",+ dimensions: [],+ metrics: [+ { measure: "count", aggregation: "count" },+ { measure: "observationsCount", aggregation: "p95" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ } as QueryType,+ ],+ [+ "trace query without metrics",+ {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ } as QueryType,+ ],+ [+ "trace query without filters",+ {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ } as QueryType,+ ],+ [+ "trace query with scores and observations",+ {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [+ {+ measure: "count",+ aggregation: "count",+ },+ {+ measure: "scoresCount",+ aggregation: "sum",+ },+ {+ measure: "observationsCount",+ aggregation: "sum",+ },+ ],+ filters: [],+ timeDimension: {+ granularity: "auto",+ },+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ } as QueryType,+ ],+ [+ "scores-numeric query",+ {+ view: "scores-numeric",+ dimensions: [{ field: "name" }],+ metrics: [+ {+ measure: "count",+ aggregation: "count",+ },+ {+ measure: "value",+ aggregation: "avg",+ },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ } as QueryType,+ ],+ [+ "scores-categorical query",+ {+ view: "scores-categorical",+ dimensions: [{ field: "name" }, { field: "stringValue" }],+ metrics: [+ {+ measure: "count",+ aggregation: "count",+ },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ } as QueryType,+ ],+ ])(+ "should compile query to valid SQL: (%s)",+ async (_name, query: QueryType) => {+ const projectId = randomUUID();++ // When+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Then+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();+ expect(result).toBeDefined();+ },+ );+ });++ describe("query result correctness", () => {+ // Helper functions+ const setupTracesWithObservations = async (+ projectId: string,+ tracesData: Array<{+ name: string;+ environment?: string;+ userId?: string;+ sessionId?: string;+ observationCount?: number;+ }>,+ ) => {+ const traces = [];++ for (const data of tracesData) {+ const trace = createTrace({+ project_id: projectId,+ name: data.name,+ environment: data.environment || "default",+ user_id: data.userId,+ session_id: data.sessionId,+ timestamp: new Date().getTime(),+ });++ traces.push(trace);++ // Create observations for this trace if specified+ if (data.observationCount && data.observationCount > 0) {+ const observations = [];++ for (let i = 0; i < data.observationCount; i++) {+ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: trace.id,+ environment: data.environment || "default",+ start_time: new Date().getTime(),+ }),+ );+ }++ await createObservationsCh(observations);+ }+ }++ await createTracesCh(traces);+ return traces;+ };++ // Helper function to create scores for testing+ const setupScores = async (+ projectId: string,+ scoresData: Array<{+ name: string;+ traceId: string;+ observationId?: string;+ value?: number;+ stringValue?: string;+ dataType: "NUMERIC" | "CATEGORICAL" | "BOOLEAN";+ source?: string;+ environment?: string;+ }>,+ ) => {+ const scores = [];++ for (const data of scoresData) {+ scores.push(+ createScore({+ project_id: projectId,+ trace_id: data.traceId,+ observation_id: data.observationId,+ name: data.name,+ value: data.dataType === "NUMERIC" ? data.value || 0 : null,+ string_value: ["CATEGORICAL", "BOOLEAN"].includes(data.dataType)+ ? data.stringValue || ""+ : null,+ environment: data.environment || "default",+ source: data.source || "API",+ data_type: data.dataType,+ }),+ );+ }++ await createScoresCh(scores);+ return scores;+ };++ describe("traces view", () => {+ it("should count traces correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "trace-1" },+ { name: "trace-2" },+ { name: "trace-3" },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query+ const query: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(), // yesterday+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(), // tomorrow+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(1);+ expect(result.data[0].count_count).toBe("3");+ });++ it("should group traces by name and count correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "chat-completion" },+ { name: "chat-completion" },+ { name: "embeddings" },+ { name: "embeddings" },+ { name: "embeddings" },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(2);++ // Find and verify each name group+ const chatCompletionRow = result.data.find(+ (row: any) => row.name === "chat-completion",+ );+ expect(chatCompletionRow.count_count).toBe("2");++ const embeddingsRow = result.data.find(+ (row: any) => row.name === "embeddings",+ );+ expect(embeddingsRow.count_count).toBe("3");+ });++ it("should filter traces by name correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "qa-bot" },+ { name: "assistant" },+ { name: "qa-bot" },+ { name: "summarizer" },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with a filter+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "name",+ operator: "=",+ value: "qa-bot",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - should only return traces with name "qa-bot"+ expect(result.data).toHaveLength(1);+ expect(result.data[0].name).toBe("qa-bot");+ expect(result.data[0].count_count).toBe("2");+ });++ it("should count observations per trace correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "trace-with-many-obs", observationCount: 5 },+ { name: "trace-with-few-obs", observationCount: 2 },+ { name: "trace-with-no-obs", observationCount: 0 },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query to count observations+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "observationsCount", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(2);++ // Find each trace by name and verify observation count+ const manyObsTrace = result.data.find(+ (row: any) => row.name === "trace-with-many-obs",+ );+ expect(manyObsTrace.sum_observations_count).toBe("5");++ const fewObsTrace = result.data.find(+ (row: any) => row.name === "trace-with-few-obs",+ );+ expect(fewObsTrace.sum_observations_count).toBe("2");+ });++ it("should group by environment and calculate metrics correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ {+ name: "trace-prod-1",+ environment: "production",+ observationCount: 3,+ },+ {+ name: "trace-prod-2",+ environment: "production",+ observationCount: 4,+ },+ {+ name: "trace-dev-1",+ environment: "development",+ observationCount: 2,+ },+ {+ name: "trace-dev-2",+ environment: "development",+ observationCount: 1,+ },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query to group by environment+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "environment" }],+ metrics: [+ { measure: "count", aggregation: "count" },+ { measure: "observationsCount", aggregation: "sum" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(2);++ // Verify production environment data+ const prodEnv = result.data.find(+ (row: any) => row.environment === "production",+ );+ expect(prodEnv.count_count).toBe("2"); // 2 traces+ expect(prodEnv.sum_observations_count).toBe("7"); // 3+4 observations++ // Verify development environment data+ const devEnv = result.data.find(+ (row: any) => row.environment === "development",+ );+ expect(devEnv.count_count).toBe("2"); // 2 traces+ expect(devEnv.sum_observations_count).toBe("3"); // 2+1 observations+ });++ it("should handle multiple dimensions (name and environment) correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "chat", environment: "production", observationCount: 2 },+ { name: "chat", environment: "development", observationCount: 1 },+ {+ name: "embeddings",+ environment: "production",+ observationCount: 3,+ },+ {+ name: "embeddings",+ environment: "development",+ observationCount: 2,+ },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with multiple dimensions+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }, { field: "environment" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(4); // 2 names × 2 environments = 4 combinations++ // Verify each combination+ const chatProd = result.data.find(+ (row: any) => row.name === "chat" && row.environment === "production",+ );+ expect(chatProd.count_count).toBe("1");++ const chatDev = result.data.find(+ (row: any) =>+ row.name === "chat" && row.environment === "development",+ );+ expect(chatDev.count_count).toBe("1");++ const embeddingsProd = result.data.find(+ (row: any) =>+ row.name === "embeddings" && row.environment === "production",+ );+ expect(embeddingsProd.count_count).toBe("1");++ const embeddingsDev = result.data.find(+ (row: any) =>+ row.name === "embeddings" && row.environment === "development",+ );+ expect(embeddingsDev.count_count).toBe("1");+ });++ it("should handle multiple metrics correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "multi-metric-test", observationCount: 10 },+ { name: "multi-metric-test", observationCount: 20 },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with multiple metrics+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "count", aggregation: "count" },+ { measure: "observationsCount", aggregation: "sum" },+ { measure: "observationsCount", aggregation: "avg" },+ { measure: "observationsCount", aggregation: "max" },+ { measure: "observationsCount", aggregation: "min" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(1);++ const row = result.data[0];+ expect(row.name).toBe("multi-metric-test");+ expect(row.count_count).toBe("2"); // 2 traces+ expect(row.sum_observations_count).toBe("30"); // 10+20 observations+ expect(row.avg_observations_count).toBe(15); // (10+20)/2 average+ expect(row.max_observations_count).toBe("20"); // max is 20+ expect(row.min_observations_count).toBe("10"); // min is 10+ });++ it("should order by a dimension field correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "trace-c", environment: "staging" },+ { name: "trace-a", environment: "production" },+ { name: "trace-b", environment: "development" },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with orderBy on a dimension+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }, { field: "environment" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: [{ field: "name", direction: "asc" }],+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify ORDER BY clause is present in the query+ expect(compiledQuery).toContain("ORDER BY name asc");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - results should be ordered by name alphabetically+ expect(result.data).toHaveLength(3);+ expect(result.data[0].name).toBe("trace-a");+ expect(result.data[1].name).toBe("trace-b");+ expect(result.data[2].name).toBe("trace-c");+ });++ it("should order by a metric field correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "trace-low", observationCount: 2 },+ { name: "trace-high", observationCount: 10 },+ { name: "trace-medium", observationCount: 5 },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with orderBy on a metric+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "observationsCount", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: [{ field: "sum_observations_count", direction: "desc" }],+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify ORDER BY clause is present in the query+ expect(compiledQuery).toContain("ORDER BY sum_observations_count desc");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - results should be ordered by observation count descending+ expect(result.data).toHaveLength(3);+ expect(result.data[0].name).toBe("trace-high"); // 10 observations+ expect(result.data[1].name).toBe("trace-medium"); // 5 observations+ expect(result.data[2].name).toBe("trace-low"); // 2 observations+ });++ it("should order by multiple fields correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "trace-a", environment: "production", observationCount: 5 },+ { name: "trace-b", environment: "production", observationCount: 2 },+ { name: "trace-c", environment: "development", observationCount: 7 },+ { name: "trace-d", environment: "development", observationCount: 3 },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with multiple orderBy fields+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "environment" }, { field: "name" }],+ metrics: [{ measure: "observationsCount", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: [+ { field: "environment", direction: "asc" },+ { field: "sum_observations_count", direction: "desc" },+ ],+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify ORDER BY clause is present in the query with both fields+ expect(compiledQuery).toContain(+ "ORDER BY environment asc, sum_observations_count desc",+ );++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - results should be ordered by environment (asc) and then by observation count (desc)+ expect(result.data).toHaveLength(4);++ // Development environment should come first (alphabetically)+ expect(result.data[0].environment).toBe("development");+ expect(result.data[1].environment).toBe("development");+ // Within development, higher observation count first+ expect(result.data[0].name).toBe("trace-c"); // 7 observations+ expect(result.data[1].name).toBe("trace-d"); // 3 observations++ // Production environment should come second+ expect(result.data[2].environment).toBe("production");+ expect(result.data[3].environment).toBe("production");+ // Within production, higher observation count first+ expect(result.data[2].name).toBe("trace-a"); // 5 observations+ expect(result.data[3].name).toBe("trace-b"); // 2 observations+ });++ it("should handle default ordering when no orderBy is specified", async () => {+ // Setup+ const projectId = randomUUID();+ const now = new Date();+ const yesterday = new Date(now);+ yesterday.setDate(yesterday.getDate() - 1);++ // Create traces with time dimension+ const traces = [+ createTrace({+ project_id: projectId,+ name: "trace-day2",+ environment: "default",+ timestamp: now.getTime(),+ }),+ createTrace({+ project_id: projectId,+ name: "trace-day1",+ environment: "default",+ timestamp: yesterday.getTime(),+ }),+ ];++ await createTracesCh(traces);++ // Define query with time dimension but no explicit orderBy+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: {+ granularity: "day",+ },+ fromTimestamp: yesterday.toISOString(),+ toTimestamp: new Date(now.getTime() + 86400000).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify ORDER BY clause includes default time dimension ordering+ expect(compiledQuery).toContain("ORDER BY time_dimension asc");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Results should be ordered by time dimension (ascending)+ expect(result.data.length).toBeGreaterThan(0);++ // Convert time_dimension strings to Date objects for comparison+ const dates = result.data.map(+ (row: any) => new Date(row.time_dimension),+ );++ // Check that dates are in ascending order+ for (let i = 1; i < dates.length; i++) {+ expect(dates[i].getTime()).toBeGreaterThanOrEqual(+ dates[i - 1].getTime(),+ );+ }+ });++ it("should use first metric for default ordering when no time dimension", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "trace-low", observationCount: 2 },+ { name: "trace-high", observationCount: 10 },+ { name: "trace-medium", observationCount: 5 },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with metrics but no explicit orderBy and no time dimension+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "observationsCount", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify ORDER BY clause includes default metric ordering (descending)+ expect(compiledQuery).toContain("ORDER BY sum_observations_count desc");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Results should be ordered by observation count descending (default for metrics)+ expect(result.data).toHaveLength(3);+ expect(result.data[0].name).toBe("trace-high"); // 10 observations+ expect(result.data[1].name).toBe("trace-medium"); // 5 observations+ expect(result.data[2].name).toBe("trace-low"); // 2 observations+ });++ it("should use first dimension for default ordering when no metrics and no time dimension", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "trace-c", environment: "production" },+ { name: "trace-a", environment: "production" },+ { name: "trace-b", environment: "production" },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with dimensions but no metrics, no time dimension, and no explicit orderBy+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify ORDER BY clause includes default dimension ordering (ascending)+ expect(compiledQuery).toContain("ORDER BY name asc");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Results should be ordered by name ascending (default for dimensions)+ expect(result.data).toHaveLength(3);+ expect(result.data[0].name).toBe("trace-a");+ expect(result.data[1].name).toBe("trace-b");+ expect(result.data[2].name).toBe("trace-c");+ });++ it("should filter with the LIKE operator correctly", async () => {+ // Setup+ const projectId = randomUUID();+ const tracesData = [+ { name: "prefix-value-1" },+ { name: "prefix-value-2" },+ { name: "different-name" },+ ];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with LIKE filter+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "name",+ operator: "starts with",+ value: "prefix-",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(2);+ expect(+ result.data.every((row: any) => row.name.startsWith("prefix-")),+ ).toBe(true);+ expect(result.data.map((row: any) => row.name).sort()).toEqual([+ "prefix-value-1",+ "prefix-value-2",+ ]);+ });++ it("should handle queries with zero dimensions and zero metrics", async () => {+ // Setup - just create a few traces+ const projectId = randomUUID();+ const tracesData = [{ name: "trace-1" }, { name: "trace-2" }];++ await setupTracesWithObservations(projectId, tracesData);++ // Define query with no dimensions and no metrics+ const query: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(1);+ expect(result.data[0].count).toBe("2"); // default count metric should be used+ });++ it("should fill gaps in time series data with WITH FILL", async () => {+ // Setup+ const projectId = randomUUID();+ const now = new Date();++ // Create traces at specific dates with intentional gaps+ const day1 = new Date(now);+ day1.setDate(day1.getDate() - 3);+ day1.setHours(12, 0, 0, 0);++ const day3 = new Date(now);+ day3.setDate(day3.getDate() - 1);+ day3.setHours(12, 0, 0, 0);++ // Skip day2 to create a gap++ const traces = [+ // Day 1 trace+ createTrace({+ project_id: projectId,+ name: "trace-test",+ environment: "default",+ timestamp: day1.getTime(),+ }),+ // Day 3 trace+ createTrace({+ project_id: projectId,+ name: "trace-test",+ environment: "default",+ timestamp: day3.getTime(),+ }),+ ];++ await createTracesCh(traces);++ // Set from timestamp to day before day1 and to timestamp to day after day3+ const fromDate = new Date(day1);+ fromDate.setDate(fromDate.getDate() - 1);++ const toDate = new Date(day3);+ toDate.setDate(toDate.getDate() + 1);++ // Define query with time dimension and daily granularity+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "name",+ operator: "=",+ value: "trace-test",+ type: "string",+ },+ ],+ timeDimension: {+ granularity: "day", // Use day granularity for clear gap visibility+ },+ fromTimestamp: fromDate.toISOString(),+ toTimestamp: toDate.toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify WITH FILL clause is present in the query+ expect(compiledQuery).toContain("WITH FILL");+ expect(compiledQuery).toContain("STEP INTERVAL 1 DAY");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Expected to have 3 days in the result (including the filled gap)+ expect(result.data.length).toBeGreaterThanOrEqual(3);++ // Convert time_dimension strings to Date objects for easier testing+ const resultDates = result.data.map((row: any) => {+ return {+ date: new Date(row.time_dimension),+ count: row.count_count ? parseInt(row.count_count) : 0,+ };+ });++ // Find day1 and day3 (where we have actual traces)+ const day1Row = resultDates.find(+ (row: any) =>+ row.date.getDate() === day1.getDate() &&+ row.date.getMonth() === day1.getMonth(),+ );++ const day3Row = resultDates.find(+ (row: any) =>+ row.date.getDate() === day3.getDate() &&+ row.date.getMonth() === day3.getMonth(),+ );++ // Find day2 (gap day that should be filled with zeros)+ const day2 = new Date(day1);+ day2.setDate(day2.getDate() + 1);++ const day2Row = resultDates.find(+ (row: any) =>+ row.date.getDate() === day2.getDate() &&+ row.date.getMonth() === day2.getMonth(),+ );++ // Assert actual data and filled gaps+ expect(day1Row?.count).toBe(1); // Actual trace for day 1+ expect(day3Row?.count).toBe(1); // Actual trace for day 3+ expect(day2Row).toBeDefined(); // Day 2 should exist (filled)+ expect(day2Row?.count).toBe(0); // Day 2 should be filled with 0++ // Check that all dates form a continuous sequence+ for (let i = 1; i < resultDates.length; i++) {+ const prevDate = resultDates[i - 1].date;+ const currDate = resultDates[i].date;++ // Difference should be approximately 1 day (86400000 ms)+ const diffMs = currDate.getTime() - prevDate.getTime();+ expect(diffMs).toBeGreaterThanOrEqual(86000000); // ~1 day with some tolerance+ expect(diffMs).toBeLessThanOrEqual(86800000); // ~1 day with some tolerance+ }+ });++ it("should group traces by name and time dimension correctly", async () => {+ // Setup+ const projectId = randomUUID();++ // Create traces with specific timestamps and names+ const now = new Date();+ const yesterday = new Date(now);+ yesterday.setDate(yesterday.getDate() - 1);+ const dayBeforeYesterday = new Date(now);+ dayBeforeYesterday.setDate(dayBeforeYesterday.getDate() - 2);++ const traces = [];+ // Today's traces - two different names+ traces.push(+ createTrace({+ project_id: projectId,+ name: "chat-completion",+ environment: "default",+ timestamp: now.getTime(),+ }),+ );+ traces.push(+ createTrace({+ project_id: projectId,+ name: "chat-completion",+ environment: "default",+ timestamp: now.getTime(),+ }),+ );+ traces.push(+ createTrace({+ project_id: projectId,+ name: "embeddings",+ environment: "default",+ timestamp: now.getTime(),+ }),+ );++ // Yesterday's traces+ traces.push(+ createTrace({+ project_id: projectId,+ name: "chat-completion",+ environment: "default",+ timestamp: yesterday.getTime(),+ }),+ );+ traces.push(+ createTrace({+ project_id: projectId,+ name: "embeddings",+ environment: "default",+ timestamp: yesterday.getTime(),+ }),+ );++ // Day before yesterday's traces+ traces.push(+ createTrace({+ project_id: projectId,+ name: "embeddings",+ environment: "default",+ timestamp: dayBeforeYesterday.getTime(),+ }),+ );++ await createTracesCh(traces);++ // Define query with time dimension and name dimension+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: {+ granularity: "day", // Group by day+ },+ fromTimestamp: dayBeforeYesterday.toISOString(),+ toTimestamp: new Date(now.getTime() + 86400000).toISOString(), // Include tomorrow+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - should have 5 combinations (chat-today, chat-yesterday, embeddings-today, embeddings-yesterday, embeddings-dayBefore)+ expect(result.data).toHaveLength(5);++ // Check chat-completion counts by day+ const chatCompletionToday = result.data.find((row: any) => {+ const rowDate = new Date(row.time_dimension);+ const today = new Date(now);+ return (+ row.name === "chat-completion" &&+ rowDate.getDate() === today.getDate() &&+ rowDate.getMonth() === today.getMonth() &&+ rowDate.getFullYear() === today.getFullYear()+ );+ });+ expect(chatCompletionToday?.count_count).toBe("2"); // 2 chat-completion traces today++ const chatCompletionYesterday = result.data.find((row: any) => {+ const rowDate = new Date(row.time_dimension);+ const yesterday = new Date(now);+ yesterday.setDate(yesterday.getDate() - 1);+ return (+ row.name === "chat-completion" &&+ rowDate.getDate() === yesterday.getDate() &&+ rowDate.getMonth() === yesterday.getMonth() &&+ rowDate.getFullYear() === yesterday.getFullYear()+ );+ });+ expect(chatCompletionYesterday?.count_count).toBe("1"); // 1 chat-completion trace yesterday++ // Check embeddings counts by day+ const embeddingsToday = result.data.find((row: any) => {+ const rowDate = new Date(row.time_dimension);+ const today = new Date(now);+ return (+ row.name === "embeddings" &&+ rowDate.getDate() === today.getDate() &&+ rowDate.getMonth() === today.getMonth() &&+ rowDate.getFullYear() === today.getFullYear()+ );+ });+ expect(embeddingsToday?.count_count).toBe("1"); // 1 embeddings trace today++ const embeddingsYesterday = result.data.find((row: any) => {+ const rowDate = new Date(row.time_dimension);+ const yesterday = new Date(now);+ yesterday.setDate(yesterday.getDate() - 1);+ return (+ row.name === "embeddings" &&+ rowDate.getDate() === yesterday.getDate() &&+ rowDate.getMonth() === yesterday.getMonth() &&+ rowDate.getFullYear() === yesterday.getFullYear()+ );+ });+ expect(embeddingsYesterday?.count_count).toBe("1"); // 1 embeddings trace yesterday++ const embeddingsDayBefore = result.data.find((row: any) => {+ const rowDate = new Date(row.time_dimension);+ const dayBefore = new Date(now);+ dayBefore.setDate(dayBefore.getDate() - 2);+ return (+ row.name === "embeddings" &&+ rowDate.getDate() === dayBefore.getDate() &&+ rowDate.getMonth() === dayBefore.getMonth() &&+ rowDate.getFullYear() === dayBefore.getFullYear()+ );+ });+ expect(embeddingsDayBefore?.count_count).toBe("1"); // 1 embeddings trace day before yesterday+ });+ });++ describe("scores-numeric view", () => {+ it("should aggregate numeric scores correctly", async () => {+ // Setup+ const projectId = randomUUID();++ // Create traces+ const traces = [+ createTrace({+ project_id: projectId,+ name: "qa-trace-1",+ environment: "production",+ }),+ createTrace({+ project_id: projectId,+ name: "qa-trace-2",+ environment: "production",+ }),+ createTrace({+ project_id: projectId,+ name: "summarization-trace",+ environment: "production",+ }),+ ];+ await createTracesCh(traces);++ // Create observations+ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: traces[0].id,+ name: "qa-observation-1",+ environment: "production",+ }),+ createObservation({+ project_id: projectId,+ trace_id: traces[1].id,+ name: "qa-observation-2",+ environment: "production",+ }),+ createObservation({+ project_id: projectId,+ trace_id: traces[2].id,+ name: "summarization-observation",+ environment: "production",+ }),+ ];+ await createObservationsCh(observations);++ // Create scores+ const scores = [+ // Accuracy scores for QA traces - different values+ {+ name: "accuracy",+ traceId: traces[0].id,+ observationId: observations[0].id,+ value: 0.85,+ dataType: "NUMERIC" as const,+ source: "human",+ },+ {+ name: "accuracy",+ traceId: traces[1].id,+ observationId: observations[1].id,+ value: 0.92,+ dataType: "NUMERIC" as const,+ source: "human",+ },++ // Relevance scores for QA traces+ {+ name: "relevance",+ traceId: traces[0].id,+ observationId: observations[0].id,+ value: 0.75,+ dataType: "NUMERIC" as const,+ source: "auto",+ },+ {+ name: "relevance",+ traceId: traces[1].id,+ observationId: observations[1].id,+ value: 0.8,+ dataType: "NUMERIC" as const,+ source: "auto",+ },++ // Coherence score for summarization trace+ {+ name: "coherence",+ traceId: traces[2].id,+ observationId: observations[2].id,+ value: 0.95,+ dataType: "NUMERIC" as const,+ source: "human",+ },++ // Adding a CATEGORICAL score that should be excluded by the segments filter+ {+ name: "evaluation",+ traceId: traces[0].id,+ observationId: observations[0].id,+ stringValue: "good",+ dataType: "CATEGORICAL" as const,+ source: "human",+ },+ ];++ await setupScores(projectId, scores);++ // Define query for numeric scores+ const query: QueryType = {+ view: "scores-numeric",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "count", aggregation: "count" },+ { measure: "value", aggregation: "avg" },+ { measure: "value", aggregation: "min" },+ { measure: "value", aggregation: "max" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify SQL includes segment filter for NUMERIC types+ expect(compiledQuery).toContain("data_type = {");+ expect(Object.values(parameters)).toContain("NUMERIC");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(3); // accuracy, relevance, coherence++ // Check each score type+ const accuracyRow = result.data.find(+ (row: any) => row.name === "accuracy",+ );+ expect(accuracyRow.count_count).toBe("2");+ expect(parseFloat(accuracyRow.avg_value)).toBeCloseTo(0.885, 2); // (0.85 + 0.92) / 2+ expect(parseFloat(accuracyRow.min_value)).toBeCloseTo(0.85, 2);+ expect(parseFloat(accuracyRow.max_value)).toBeCloseTo(0.92, 2);++ const relevanceRow = result.data.find(+ (row: any) => row.name === "relevance",+ );+ expect(relevanceRow.count_count).toBe("2");+ expect(parseFloat(relevanceRow.avg_value)).toBeCloseTo(0.775, 2); // (0.75 + 0.80) / 2+ expect(parseFloat(relevanceRow.min_value)).toBeCloseTo(0.75, 2);+ expect(parseFloat(relevanceRow.max_value)).toBeCloseTo(0.8, 2);++ const coherenceRow = result.data.find(+ (row: any) => row.name === "coherence",+ );+ expect(coherenceRow.count_count).toBe("1");+ expect(parseFloat(coherenceRow.avg_value)).toBeCloseTo(0.95, 2);+ });++ it("should filter numeric scores by source", async () => {+ // Setup+ const projectId = randomUUID();++ // Create trace+ const trace = createTrace({+ project_id: projectId,+ name: "qa-trace",+ environment: "production",+ });+ await createTracesCh([trace]);++ // Create observation+ const observation = createObservation({+ project_id: projectId,+ trace_id: trace.id,+ name: "qa-observation",+ environment: "production",+ });+ await createObservationsCh([observation]);++ // Create scores with different sources+ const scores = [+ {+ name: "quality",+ traceId: trace.id,+ observationId: observation.id,+ value: 0.95,+ dataType: "NUMERIC" as const,+ source: "human",+ },+ {+ name: "quality",+ traceId: trace.id,+ observationId: observation.id,+ value: 0.88,+ dataType: "NUMERIC" as const,+ source: "auto",+ },+ {+ name: "quality",+ traceId: trace.id,+ observationId: observation.id,+ value: 0.92,+ dataType: "NUMERIC" as const,+ source: "external",+ },+ ];++ await setupScores(projectId, scores);++ // Define query with filter for human-source scores+ const query: QueryType = {+ view: "scores-numeric",+ dimensions: [{ field: "source" }],+ metrics: [+ { measure: "count", aggregation: "count" },+ { measure: "value", aggregation: "avg" },+ ],+ filters: [+ {+ column: "source",+ operator: "=",+ value: "human",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - should only return human scores+ expect(result.data).toHaveLength(1);+ expect(result.data[0].source).toBe("human");+ expect(result.data[0].count_count).toBe("1");+ expect(parseFloat(result.data[0].avg_value)).toBeCloseTo(0.95, 2);+ });++ it("should join with traces and observations to get related dimensions", async () => {+ // Setup+ const projectId = randomUUID();++ // Create traces with different names+ const traces = [+ createTrace({+ project_id: projectId,+ name: "qa-trace",+ environment: "production",+ user_id: "user-1",+ }),+ createTrace({+ project_id: projectId,+ name: "summarization-trace",+ environment: "production",+ user_id: "user-2",+ }),+ ];+ await createTracesCh(traces);++ // Create observations with different model names+ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: traces[0].id,+ name: "qa-observation",+ environment: "production",+ provided_model_name: "gpt-4",+ }),+ createObservation({+ project_id: projectId,+ trace_id: traces[1].id,+ name: "summarization-observation",+ environment: "production",+ provided_model_name: "claude-3",+ }),+ ];+ await createObservationsCh(observations);++ // Create numeric scores+ const scores = [+ {+ name: "accuracy",+ traceId: traces[0].id,+ observationId: observations[0].id,+ value: 0.9,+ dataType: "NUMERIC" as const,+ },+ {+ name: "relevance",+ traceId: traces[0].id,+ observationId: observations[0].id,+ value: 0.85,+ dataType: "NUMERIC" as const,+ },+ {+ name: "accuracy",+ traceId: traces[1].id,+ observationId: observations[1].id,+ value: 0.95,+ dataType: "NUMERIC" as const,+ },+ ];++ await setupScores(projectId, scores);++ // Define query to group by trace name and observation model+ const query: QueryType = {+ view: "scores-numeric",+ dimensions: [+ { field: "traceName" },+ { field: "observationModelName" },+ ],+ metrics: [+ { measure: "count", aggregation: "count" },+ { measure: "value", aggregation: "avg" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify joins included+ expect(compiledQuery).toContain("LEFT JOIN traces");+ expect(compiledQuery).toContain("LEFT JOIN observations");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - should have 2 rows (1 for each trace/model combination)+ expect(result.data).toHaveLength(2);++ // Check qa trace with gpt-4+ const qaTraceRow = result.data.find(+ (row: any) =>+ row.trace_name === "qa-trace" &&+ row.observation_model_name === "gpt-4",+ );+ expect(qaTraceRow.count_count).toBe("2"); // 2 scores (accuracy + relevance)+ expect(parseFloat(qaTraceRow.avg_value)).toBeCloseTo(0.875, 2); // (0.90 + 0.85) / 2++ // Check summarization trace with claude-3+ const summaryTraceRow = result.data.find(+ (row: any) =>+ row.trace_name === "summarization-trace" &&+ row.observation_model_name === "claude-3",+ );+ expect(summaryTraceRow.count_count).toBe("1"); // 1 score (accuracy)+ expect(parseFloat(summaryTraceRow.avg_value)).toBeCloseTo(0.95, 2);+ });+ });++ describe("scores-categorical view", () => {+ it("should group categorical scores by value correctly", async () => {+ // Setup+ const projectId = randomUUID();++ // Create trace+ const trace = createTrace({+ project_id: projectId,+ name: "trace-with-categorical-scores",+ environment: "production",+ });+ await createTracesCh([trace]);++ // Create observation+ const observation = createObservation({+ project_id: projectId,+ trace_id: trace.id,+ name: "observation",+ environment: "production",+ });+ await createObservationsCh([observation]);++ // Create categorical and boolean scores+ const scores = [+ // Categorical scores+ {+ name: "evaluation",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "excellent",+ dataType: "CATEGORICAL" as const,+ source: "human",+ },+ {+ name: "evaluation",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "good",+ dataType: "CATEGORICAL" as const,+ source: "human",+ },+ {+ name: "evaluation",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "good",+ dataType: "CATEGORICAL" as const,+ source: "human",+ },+ {+ name: "category",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "question",+ dataType: "CATEGORICAL" as const,+ source: "auto",+ },+ {+ name: "category",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "factual",+ dataType: "CATEGORICAL" as const,+ source: "auto",+ },++ // Boolean scores+ {+ name: "is_correct",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "true",+ dataType: "BOOLEAN" as const,+ source: "auto",+ },+ {+ name: "is_correct",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "false",+ dataType: "BOOLEAN" as const,+ source: "auto",+ },++ // Adding a NUMERIC score that should be excluded by the segments filter+ {+ name: "numeric_score",+ traceId: trace.id,+ observationId: observation.id,+ value: 0.95,+ dataType: "NUMERIC" as const,+ source: "human",+ },+ ];++ await setupScores(projectId, scores);++ // Define query to count by score name and string value+ const query: QueryType = {+ view: "scores-categorical",+ dimensions: [{ field: "name" }, { field: "stringValue" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Verify SQL includes segment filter for non-NUMERIC types+ expect(compiledQuery).toContain(+ "position(scores_categorical.data_type, {",+ );+ expect(compiledQuery).toContain(": String}) = 0");+ expect(Object.values(parameters)).toContain("NUMERIC");++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - should have 6 rows for different name+value combinations+ expect(result.data).toHaveLength(6);++ // Check each combination+ const evaluationExcellent = result.data.find(+ (row: any) =>+ row.name === "evaluation" && row.string_value === "excellent",+ );+ expect(evaluationExcellent.count_count).toBe("1");++ const evaluationGood = result.data.find(+ (row: any) =>+ row.name === "evaluation" && row.string_value === "good",+ );+ expect(evaluationGood.count_count).toBe("2");++ const categoryQuestion = result.data.find(+ (row: any) =>+ row.name === "category" && row.string_value === "question",+ );+ expect(categoryQuestion.count_count).toBe("1");++ const categoryFactual = result.data.find(+ (row: any) =>+ row.name === "category" && row.string_value === "factual",+ );+ expect(categoryFactual.count_count).toBe("1");++ // Check boolean scores+ const isCorrectTrue = result.data.find(+ (row: any) =>+ row.name === "is_correct" && row.string_value === "true",+ );+ expect(isCorrectTrue.count_count).toBe("1");++ const isCorrectFalse = result.data.find(+ (row: any) =>+ row.name === "is_correct" && row.string_value === "false",+ );+ expect(isCorrectFalse.count_count).toBe("1");+ });++ it("should filter categorical scores by source", async () => {+ // Setup+ const projectId = randomUUID();++ // Create trace+ const trace = createTrace({+ project_id: projectId,+ name: "trace",+ environment: "production",+ });+ await createTracesCh([trace]);++ // Create observation+ const observation = createObservation({+ project_id: projectId,+ trace_id: trace.id,+ name: "observation",+ environment: "production",+ });+ await createObservationsCh([observation]);++ // Create categorical scores with different sources+ const scores = [+ {+ name: "classification",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "question",+ dataType: "CATEGORICAL" as const,+ source: "human",+ },+ {+ name: "classification",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "statement",+ dataType: "CATEGORICAL" as const,+ source: "auto",+ },+ {+ name: "classification",+ traceId: trace.id,+ observationId: observation.id,+ stringValue: "command",+ dataType: "CATEGORICAL" as const,+ source: "auto",+ },+ ];++ await setupScores(projectId, scores);++ // Define query with filter for auto-source scores only+ const query: QueryType = {+ view: "scores-categorical",+ dimensions: [{ field: "stringValue" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "source",+ operator: "=",+ value: "auto",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - should only return auto-source scores+ expect(result.data).toHaveLength(2);+ expect(result.data.every((row: any) => row.count_count === "1")).toBe(+ true,+ );++ // Check specific values+ const stringValues = result.data+ .map((row: any) => row.string_value)+ .sort();+ expect(stringValues).toEqual(["command", "statement"]);+ });++ it("should filter boolean scores correctly", async () => {+ // Setup+ const projectId = randomUUID();++ // Create traces+ const traces = [+ createTrace({+ project_id: projectId,+ name: "trace-1",+ environment: "production",+ }),+ createTrace({+ project_id: projectId,+ name: "trace-2",+ environment: "production",+ }),+ ];+ await createTracesCh(traces);++ // Create observations+ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: traces[0].id,+ name: "observation-1",+ environment: "production",+ }),+ createObservation({+ project_id: projectId,+ trace_id: traces[1].id,+ name: "observation-2",+ environment: "production",+ }),+ ];+ await createObservationsCh(observations);++ // Create boolean scores+ const scores = [+ {+ name: "is_hallucination",+ traceId: traces[0].id,+ observationId: observations[0].id,+ stringValue: "true",+ dataType: "BOOLEAN" as const,+ },+ {+ name: "is_hallucination",+ traceId: traces[1].id,+ observationId: observations[1].id,+ stringValue: "false",+ dataType: "BOOLEAN" as const,+ },+ {+ name: "is_helpful",+ traceId: traces[0].id,+ observationId: observations[0].id,+ stringValue: "false",+ dataType: "BOOLEAN" as const,+ },+ {+ name: "is_helpful",+ traceId: traces[1].id,+ observationId: observations[1].id,+ stringValue: "true",+ dataType: "BOOLEAN" as const,+ },+ ];++ await setupScores(projectId, scores);++ // Define query to filter for true Boolean scores only+ const query: QueryType = {+ view: "scores-categorical",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "stringValue",+ operator: "=",+ value: "true",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );+ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert - should only return true scores+ expect(result.data).toHaveLength(2);++ // Check which scores were true+ const isHallucination = result.data.find(+ (row: any) => row.name === "is_hallucination",+ );+ const isHelpful = result.data.find(+ (row: any) => row.name === "is_helpful",+ );++ expect(isHallucination.count_count).toBe("1");+ expect(isHelpful.count_count).toBe("1");+ });+ });++ describe("observations view", () => {+ it("should calculate p95 timeToFirstToken for each trace name using observations view", async () => {+ // Setup+ const projectId = randomUUID();++ // Create traces with observations that have different start/completion start times+ const traces = [];+ const observations = [];++ // Create trace for "gpt-4-turbo" model+ const traceGpt4 = createTrace({+ project_id: projectId,+ name: "gpt-4-completion",+ environment: "default",+ timestamp: new Date().getTime(),+ });+ traces.push(traceGpt4);++ // Create observations for GPT-4-turbo with different time to first token values+ // Add 10 observations with time to first token ranging from 500ms to 1400ms+ for (let i = 0; i < 10; i++) {+ const startTime = new Date();+ // Create increasing TTFT values (500ms to 1400ms)+ const ttft = 500 + i * 100;+ const completionStartTime = new Date(startTime.getTime() + ttft);+ const endTime = new Date(completionStartTime.getTime() + 500); // Add another 500ms for generation++ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: traceGpt4.id,+ type: "generation",+ name: "gpt-4-turbo",+ provided_model_name: "gpt-4-turbo",+ environment: "default",+ start_time: startTime.getTime(),+ completion_start_time: completionStartTime.getTime(),+ end_time: endTime.getTime(),+ }),+ );+ }++ // Create trace for "gpt-3.5-turbo" model+ const traceGpt35 = createTrace({+ project_id: projectId,+ name: "gpt-3.5-completion",+ environment: "default",+ timestamp: new Date().getTime(),+ });+ traces.push(traceGpt35);++ // Create observations for GPT-3.5-turbo with different time to first token values+ // Add 10 observations with time to first token ranging from 200ms to 650ms+ for (let i = 0; i < 10; i++) {+ const startTime = new Date();+ // Create increasing TTFT values (200ms to 650ms)+ const ttft = 200 + i * 50;+ const completionStartTime = new Date(startTime.getTime() + ttft);+ const endTime = new Date(completionStartTime.getTime() + 300); // Add another 300ms for generation++ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: traceGpt35.id,+ type: "generation",+ name: "gpt-3.5-turbo",+ provided_model_name: "gpt-3.5-turbo",+ environment: "default",+ start_time: startTime.getTime(),+ completion_start_time: completionStartTime.getTime(),+ end_time: endTime.getTime(),+ }),+ );+ }++ // Create trace for "claude-3-opus" model+ const traceClaude = createTrace({+ project_id: projectId,+ name: "claude-completion",+ environment: "default",+ timestamp: new Date().getTime(),+ });+ traces.push(traceClaude);++ // Create observations for Claude with different time to first token values+ // Add 10 observations with time to first token ranging from 300ms to 1200ms+ for (let i = 0; i < 10; i++) {+ const startTime = new Date();+ // Create increasing TTFT values (300ms to 1200ms)+ const ttft = 300 + i * 100;+ const completionStartTime = new Date(startTime.getTime() + ttft);+ const endTime = new Date(completionStartTime.getTime() + 400); // Add another 400ms for generation++ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: traceClaude.id,+ type: "generation",+ name: "claude-3-opus",+ provided_model_name: "claude-3-opus",+ environment: "default",+ start_time: startTime.getTime(),+ completion_start_time: completionStartTime.getTime(),+ end_time: endTime.getTime(),+ }),+ );+ }++ await createTracesCh(traces);+ await createObservationsCh(observations);++ // Define query to test p95 timeToFirstToken calculation for each trace using observations view+ const query: QueryType = {+ view: "observations",+ dimensions: [{ field: "traceName" }],+ metrics: [{ measure: "timeToFirstToken", aggregation: "p95" }],+ filters: [+ {+ column: "type",+ operator: "=",+ value: "generation",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: new Date(+ new Date().setDate(new Date().getDate() - 1),+ ).toISOString(),+ toTimestamp: new Date(+ new Date().setDate(new Date().getDate() + 1),+ ).toISOString(),+ orderBy: null,+ };++ // Execute query+ const queryBuilder = new QueryBuilder();+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ const result = await (+ await clickhouseClient().query({+ query: compiledQuery,+ query_params: parameters,+ })+ ).json();++ // Assert+ expect(result.data).toHaveLength(3);++ // Get results for each trace+ const gpt4Result = result.data.find(+ (row: any) => row.trace_name === "gpt-4-completion",+ );+ const gpt35Result = result.data.find(+ (row: any) => row.trace_name === "gpt-3.5-completion",+ );+ const claudeResult = result.data.find(+ (row: any) => row.trace_name === "claude-completion",+ );++ // The p95 should be close to the 95th percentile value we generated+ // For GPT-4: the 95th percentile of values from 500-1400 would be around 1350ms+ expect(+ parseInt(gpt4Result.p95_time_to_first_token),+ ).toBeGreaterThanOrEqual(1300);+ expect(+ parseInt(gpt4Result.p95_time_to_first_token),+ ).toBeLessThanOrEqual(1400);++ // For GPT-3.5: the 95th percentile of values from 200-650 would be around 625ms+ expect(+ parseInt(gpt35Result.p95_time_to_first_token),+ ).toBeGreaterThanOrEqual(600);+ expect(+ parseInt(gpt35Result.p95_time_to_first_token),+ ).toBeLessThanOrEqual(650);++ // For Claude: the 95th percentile of values from 300-1200 would be around 1150ms+ expect(+ parseInt(claudeResult.p95_time_to_first_token),+ ).toBeGreaterThanOrEqual(1100);+ expect(+ parseInt(claudeResult.p95_time_to_first_token),+ ).toBeLessThanOrEqual(1200);+ });+ });+ });+});diff --git a/web/src/__tests__/queryBuilderDashboards.servertest.ts b/web/src/__tests__/queryBuilderDashboards.servertest.tsnew file mode 100644index 0000000000..7c56a1b6fd--- /dev/null+++ b/web/src/__tests__/queryBuilderDashboards.servertest.ts@@ -0,0 +1,903 @@+import { randomUUID } from "crypto";+import {+ createTrace,+ createTracesCh,+ createObservation,+ createObservationsCh,+ getTotalTraces,+ getTracesGroupedByName,+ getObservationsCostGroupedByName,+ getScoreAggregate,+ groupTracesByTime,+} from "@langfuse/shared/src/server";+import { type FilterState } from "@langfuse/shared";+import { type QueryType } from "@/src/features/query/types";+import { executeQuery } from "@/src/features/dashboard/server/dashboard-router";+import { dashboardColumnDefinitions } from "@langfuse/shared";++/**+ * Test suite for testing the self-serve dashboards functionality+ * This tests that the new query builder produces the same results as the existing dashboard queries+ */+describe("selfServeDashboards", () => {+ // Single project ID for all tests+ const projectId = randomUUID();++ // Time references+ const now = new Date();+ const oneHourAgo = new Date(now.getTime() - 3600000);+ const twoHoursAgo = new Date(now.getTime() - 7200000);+ const threeDaysAgo = new Date(now.getTime() - 3 * 24 * 3600000);++ // Time ranges for queries - converted to ClickHouse DateTime format (YYYY-MM-DD HH:MM:SS.SSS)+ const defaultFromTime = threeDaysAgo.toISOString();+ const defaultToTime = new Date(now.getTime() + 3600000).toISOString(); // 1 hour in future++ // Test data statistics for verification+ const stats = {+ totalTraces: 0,+ productionTraces: 0,+ developmentTraces: 0,+ stagingTraces: 0,+ recentProductionTraces: 0, // within the last hour+ traceCounts: {} as Record<string, number>, // counts by trace name+ environmentCounts: {} as Record<string, number>, // counts by environment+ };++ beforeAll(async () => {+ // Create a diverse set of traces with different characteristics+ const traces = [+ // Production environment - common names+ ...Array(5)+ .fill(0)+ .map((_, i) =>+ createTrace({+ project_id: projectId,+ name: "chat-completion",+ environment: "production",+ timestamp: now.getTime() - i * 10000, // Slightly different timestamps+ user_id: "user-A",+ }),+ ),+ ...Array(3)+ .fill(0)+ .map((_, i) =>+ createTrace({+ project_id: projectId,+ name: "embeddings",+ environment: "production",+ timestamp: now.getTime() - i * 15000,+ user_id: "user-B",+ }),+ ),++ // Production environment - older traces+ ...Array(2)+ .fill(0)+ .map((_, i) =>+ createTrace({+ project_id: projectId,+ name: "chat-completion",+ environment: "production",+ timestamp: twoHoursAgo.getTime() - i * 10000,+ user_id: "user-C",+ }),+ ),++ // Development environment - recent+ ...Array(4)+ .fill(0)+ .map((_, i) =>+ createTrace({+ project_id: projectId,+ name: "chat-completion",+ environment: "development",+ timestamp: oneHourAgo.getTime() - i * 20000,+ user_id: "user-D",+ }),+ ),+ ...Array(2)+ .fill(0)+ .map((_, i) =>+ createTrace({+ project_id: projectId,+ name: "summarize",+ environment: "development",+ timestamp: now.getTime() - i * 5000,+ user_id: "user-E",+ }),+ ),++ // Staging environment+ ...Array(3)+ .fill(0)+ .map((_, i) =>+ createTrace({+ project_id: projectId,+ name: "qa-bot",+ environment: "staging",+ timestamp: now.getTime() - i * 30000,+ user_id: "user-F",+ }),+ ),+ ];++ // Insert traces into ClickHouse+ await createTracesCh(traces);++ // Create observations for some of these traces+ const observations = [];++ // Add observations for chat-completion traces in production+ for (let i = 0; i < 3; i++) {+ const traceId = traces[i].id;+ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: traceId,+ name: "gpt-4-turbo",+ type: "generation",+ environment: "production",+ start_time: now.getTime() - i * 10000,+ completion_start_time: now.getTime() - i * 10000 + 800, // 800ms time to first token+ end_time: now.getTime() - i * 10000 + 3000, // 3000ms total duration+ provided_model_name: "gpt-4-turbo",+ }),+ );+ }++ // Add observations for embeddings traces+ for (let i = 0; i < 2; i++) {+ const traceId = traces[5 + i].id; // embeddings traces start at index 5+ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: traceId,+ name: "text-embedding-ada-002",+ type: "generation",+ environment: "production",+ start_time: now.getTime() - i * 15000,+ completion_start_time: now.getTime() - i * 15000 + 200, // 200ms time to first token+ end_time: now.getTime() - i * 15000 + 500, // 500ms total duration+ provided_model_name: "text-embedding-ada-002",+ }),+ );+ }++ // Add observations for development traces+ for (let i = 0; i < 2; i++) {+ const traceId = traces[10 + i].id; // development traces start at index 10+ observations.push(+ createObservation({+ project_id: projectId,+ trace_id: traceId,+ name: "claude-3-opus",+ type: "generation",+ environment: "development",+ start_time: oneHourAgo.getTime() - i * 20000,+ completion_start_time: oneHourAgo.getTime() - i * 20000 + 1200, // 1200ms time to first token+ end_time: oneHourAgo.getTime() - i * 20000 + 4000, // 4000ms total duration+ provided_model_name: "claude-3-opus",+ }),+ );+ }++ // Insert observations into ClickHouse+ await createObservationsCh(observations);++ // Calculate statistics for verification+ stats.totalTraces = traces.length;++ // Count by environment+ traces.forEach((trace) => {+ stats.environmentCounts[trace.environment] =+ (stats.environmentCounts[trace.environment] || 0) + 1;+ });+ stats.productionTraces = stats.environmentCounts["production"] || 0;+ stats.developmentTraces = stats.environmentCounts["development"] || 0;+ stats.stagingTraces = stats.environmentCounts["staging"] || 0;++ // Count traces by name+ traces.forEach((trace) => {+ stats.traceCounts[trace.name || ""] =+ (stats.traceCounts[trace.name || ""] || 0) + 1;+ });++ // Count recent production traces (within the last hour)+ stats.recentProductionTraces = traces.filter(+ (t) =>+ t.environment === "production" && t.timestamp >= oneHourAgo.getTime(),+ ).length;+ });++ describe("traces-total query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // Empty filter for this test+ const filter: FilterState = [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date("1970-01-02"),+ },+ ];++ // 1. Get result using the legacy function+ const legacyResult = await getTotalTraces(projectId, filter);++ // 2. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 4. Assert that both results match+ expect(queryBuilderResult).toHaveLength(1);+ expect(Number(queryBuilderResult[0].count_count)).toBe(stats.totalTraces);+ expect(Number(legacyResult?.[0]?.countTraceId)).toBe(stats.totalTraces);+ });++ it("should filter traces by environment correctly", async () => {+ // 1. Define a filter for production environment in the legacy format+ const prodLegacyFilter: FilterState = [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date("1970-01-02"),+ },+ {+ type: "string",+ operator: "=",+ column: "environment",+ value: "production",+ },+ ];+ const prodLegacyResult = await getTotalTraces(+ projectId,+ prodLegacyFilter,+ );++ // 2. Define the equivalent query with filter for the query builder+ const prodQueryBuilderQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "environment",+ operator: "=",+ value: "production",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };+ const prodQueryBuilderResult = await executeQuery(+ projectId,+ prodQueryBuilderQuery,+ );++ // 3. Assert that both results match and only count production traces+ expect(prodQueryBuilderResult).toHaveLength(1);+ expect(Number(prodQueryBuilderResult[0].count_count)).toBe(+ stats.productionTraces,+ );+ expect(Number(prodLegacyResult?.[0]?.countTraceId)).toBe(+ stats.productionTraces,+ );++ // 4. Test another filter for development environment+ const devLegacyFilter: FilterState = [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date("1970-01-02"),+ },+ {+ type: "string",+ operator: "=",+ column: "environment",+ value: "development",+ },+ ];+ const devLegacyResult = await getTotalTraces(projectId, devLegacyFilter);++ const devQueryBuilderQuery: QueryType = {+ ...prodQueryBuilderQuery,+ filters: [+ {+ column: "environment",+ operator: "=",+ value: "development",+ type: "string",+ },+ ],+ };+ const devQueryBuilderResult = await executeQuery(+ projectId,+ devQueryBuilderQuery,+ );++ // 5. Assert development environment results+ expect(devQueryBuilderResult).toHaveLength(1);+ expect(Number(devQueryBuilderResult[0].count_count)).toBe(+ stats.developmentTraces,+ );+ expect(Number(devLegacyResult?.[0]?.countTraceId)).toBe(+ stats.developmentTraces,+ );+ });++ it("should handle multiple filter conditions", async () => {+ // 1. Define a filter for recent production traces in the legacy format+ const recentProdLegacyFilter: FilterState = [+ {+ type: "string",+ operator: "=",+ column: "environment",+ value: "production",+ },+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: oneHourAgo,+ },+ ];+ const legacyResult = await getTotalTraces(+ projectId,+ recentProdLegacyFilter,+ );++ // 2. Define the equivalent query with multiple filters for the query builder+ const queryBuilderQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "environment",+ operator: "=",+ value: "production",+ type: "string",+ },+ {+ column: "timestamp",+ operator: ">=",+ value: new Date(oneHourAgo),+ type: "datetime",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 3. Assert that both results match and only count recent production traces+ expect(queryBuilderResult).toHaveLength(1);+ expect(Number(queryBuilderResult[0].count_count)).toBe(+ stats.recentProductionTraces,+ );+ expect(legacyResult?.[0]?.countTraceId).toBe(+ `${stats.recentProductionTraces}`,+ );+ });+ });++ describe("traces-grouped-by-name query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // 1. Get result using the legacy function+ const legacyResult = await getTracesGroupedByName(+ projectId,+ dashboardColumnDefinitions,+ [], // empty filter+ );++ // 2. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 4. Verify both results+ const legacyResultMap = new Map(+ legacyResult.map((item) => [item.name, item.count]),+ );++ // Verify results match the expected trace counts by name+ Object.keys(stats.traceCounts).forEach((traceName) => {+ const countFromLegacy = legacyResultMap.get(traceName);+ const resultRow = queryBuilderResult.find(+ (row: any) => row.name === traceName,+ );++ expect(countFromLegacy).toBe(`${stats.traceCounts[traceName]}`);+ expect(Number(resultRow?.count_count)).toBe(+ stats.traceCounts[traceName],+ );+ });++ // Verify both result sets have the same number of rows+ expect(legacyResult.length).toBe(Object.keys(stats.traceCounts).length);+ expect(queryBuilderResult.length).toBe(+ Object.keys(stats.traceCounts).length,+ );+ });++ it("should filter traces by environment when grouping by name", async () => {+ // 1. Define a filter for production environment+ const prodFilter: FilterState = [+ {+ type: "string",+ operator: "=",+ column: "environment",+ value: "production",+ },+ ];++ // 2. Get legacy result with filter+ const legacyResult = await getTracesGroupedByName(+ projectId,+ dashboardColumnDefinitions,+ prodFilter,+ );++ // 3. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "environment",+ operator: "=",+ value: "production",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 4. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 5. Verify results+ // Get only traces with production environment+ const productionTraceNames = ["chat-completion", "embeddings"];++ // Verify both results have the expected number of rows+ expect(legacyResult.length).toBe(productionTraceNames.length);+ expect(queryBuilderResult.length).toBe(productionTraceNames.length);++ // Create easy-to-use maps for comparison+ const legacyResultMap = new Map(+ legacyResult.map((item) => [item.name, item.count]),+ );++ // Check each production trace name is present with correct count+ productionTraceNames.forEach((traceName) => {+ const countFromLegacy = legacyResultMap.get(traceName);+ const resultRow = queryBuilderResult.find(+ (row: any) => row.name === traceName,+ );++ expect(countFromLegacy).toBeDefined();+ expect(resultRow).toBeDefined();+ expect(resultRow?.count_count).toBe(countFromLegacy);+ });+ });+ });++ describe("observations-model-cost query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // 1. Get result using the legacy function+ const legacyResult = await getObservationsCostGroupedByName(+ projectId,+ [], // empty filter+ );++ // 2. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "providedModelName" }],+ metrics: [+ { measure: "totalCost", aggregation: "sum" },+ { measure: "totalTokens", aggregation: "sum" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 4. Verify both results+ expect(queryBuilderResult).toBeDefined();+ expect(legacyResult).toBeDefined();++ // Create maps for easier comparison+ const legacyResultMap = new Map(+ legacyResult.map((item) => [item.name, item]),+ );++ // Verify each model's costs and token usage match+ queryBuilderResult.forEach((row: any) => {+ const modelName = row.provided_model_name;+ const legacyModelData = legacyResultMap.get(modelName);++ expect(legacyModelData).toBeDefined();+ expect(row.sum_total_cost).toBe(legacyModelData?.sum_cost_details);+ expect(row.sum_total_tokens).toBe(legacyModelData?.sum_usage_details);+ });++ // Verify both result sets have the same number of models+ expect(legacyResult.length).toBe(queryBuilderResult.length);+ });++ it("should filter observations by environment", async () => {+ // 1. Define a filter for production environment+ const prodFilter: FilterState = [+ {+ type: "string",+ operator: "=",+ column: "environment",+ value: "production",+ },+ ];++ // 2. Get legacy result with filter+ const legacyResult = await getObservationsCostGroupedByName(+ projectId,+ prodFilter,+ );++ // 3. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "observations",+ dimensions: [{ field: "providedModelName" }],+ metrics: [+ { measure: "totalCost", aggregation: "sum" },+ { measure: "totalTokens", aggregation: "sum" },+ ],+ filters: [+ {+ column: "environment",+ operator: "=",+ value: "production",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 4. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 5. Verify results+ // Production models should only include gpt-4-turbo and text-embedding-ada-002+ const productionModels = ["gpt-4-turbo", "text-embedding-ada-002"];++ // Verify both results have the expected number of rows+ expect(legacyResult.length).toBe(productionModels.length);+ expect(queryBuilderResult.length).toBe(productionModels.length);++ // Create maps for easier comparison+ const legacyResultMap = new Map(+ legacyResult.map((item) => [item.name, item]),+ );++ // Verify each production model is present with correct costs+ queryBuilderResult.forEach((row: any) => {+ const modelName = row.provided_model_name;+ const legacyModelData = legacyResultMap.get(modelName);++ expect(productionModels).toContain(modelName);+ expect(legacyModelData).toBeDefined();+ expect(row.sum_total_cost).toBe(legacyModelData?.sum_cost_details);+ expect(row.sum_total_tokens).toBe(legacyModelData?.sum_usage_details);+ });+ });+ });++ describe("score-aggregate query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // 1. Get result using the legacy function+ const legacyResult = await getScoreAggregate(projectId, [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date("1970-01-02"),+ },+ ]);++ // 2. Define the equivalent query for the query builder+ const queryBuilderNumericQuery: QueryType = {+ view: "scores-numeric",+ dimensions: [+ { field: "name" },+ { field: "source" },+ { field: "dataType" },+ ],+ metrics: [+ { measure: "value", aggregation: "avg" },+ { measure: "count", aggregation: "count" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get results using the query builder for numeric scores+ const queryBuilderNumericResult = await executeQuery(+ projectId,+ queryBuilderNumericQuery,+ );++ // 4. Check categorical scores separately (optional, as the test dataset may not include them)+ const queryCategoricalQuery: QueryType = {+ view: "scores-categorical",+ dimensions: [+ { field: "name" },+ { field: "source" },+ { field: "dataType" },+ ],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Get results for categorical scores+ const queryBuilderCatResult = await executeQuery(+ projectId,+ queryCategoricalQuery,+ );++ // 5. Verify both results+ expect(queryBuilderNumericResult).toBeDefined();+ expect(legacyResult).toBeDefined();++ // Check that all numeric scores from legacy query are present in new query+ // Note: This test assumes numeric scores. If you have categorical scores, you'd need to+ // handle them separately by checking against queryBuilderCatResult+ legacyResult.forEach((legacyScore) => {+ // Only check numeric scores here+ if (legacyScore.data_type === "numeric") {+ const matchingRow = queryBuilderNumericResult.find(+ (row: any) =>+ row.name === legacyScore.name &&+ row.source === legacyScore.source &&+ row.data_type === legacyScore.data_type,+ );++ expect(matchingRow).toBeDefined();+ // Check count matches+ expect(Number(matchingRow?.count_count)).toBe(+ Number(legacyScore.count),+ );+ // Check average value is approximately the same+ expect(Number(matchingRow?.value_avg)).toBeCloseTo(+ Number(legacyScore.avg_value),+ );+ }+ });++ // If we have categorical scores in our test data, verify those too+ const categoricalScores = legacyResult.filter(+ (score) => score.data_type === "categorical",+ );+ if (categoricalScores.length > 0 && queryBuilderCatResult.length > 0) {+ categoricalScores.forEach((legacyScore) => {+ const matchingRow = queryBuilderCatResult.find(+ (row: any) =>+ row.name === legacyScore.name &&+ row.source === legacyScore.source &&+ row.data_type === legacyScore.data_type,+ );++ expect(matchingRow).toBeDefined();+ // Check count matches+ expect(Number(matchingRow?.count_count)).toBe(+ Number(legacyScore.count),+ );+ });+ }+ });++ it("should filter scores by environment", async () => {+ // 1. Define a filter for production environment+ const prodFilter: FilterState = [+ {+ type: "string",+ operator: "=",+ column: "environment",+ value: "production",+ },+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date("1970-01-02"),+ },+ ];++ // 2. Get legacy result with filter+ const legacyResult = await getScoreAggregate(projectId, prodFilter);++ // 3. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "scores-numeric", // We'll just test numeric scores for simplicity+ dimensions: [+ { field: "name" },+ { field: "source" },+ { field: "dataType" },+ ],+ metrics: [+ { measure: "value", aggregation: "avg" },+ { measure: "count", aggregation: "count" },+ ],+ filters: [+ {+ column: "environment",+ operator: "=",+ value: "production",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 4. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 5. Verify results+ // Production environment should only include certain scores (based on test data)+ // We can check if both results have the same number of scores for production+ expect(queryBuilderResult.length).toBe(+ legacyResult.filter((score) => score.data_type === "numeric").length,+ );++ // Check that all numeric scores in production environment from legacy query match the new query+ legacyResult+ .filter((score) => score.data_type === "numeric")+ .forEach((legacyScore) => {+ const matchingRow = queryBuilderResult.find(+ (row: any) =>+ row.name === legacyScore.name &&+ row.source === legacyScore.source &&+ row.data_type === legacyScore.data_type,+ );++ expect(matchingRow).toBeDefined();+ // Check count matches+ expect(Number(matchingRow?.count_count)).toBe(+ Number(legacyScore.count),+ );+ // Check average value is approximately the same+ expect(Number(matchingRow?.value_avg)).toBeCloseTo(+ Number(legacyScore.avg_value),+ );+ });+ });+ });++ describe("traces-timeseries query", () => {+ it("should return the same result with query builder as with legacy function", async () => {+ // 1. Get result using the legacy function+ const legacyResult = await groupTracesByTime(projectId, [+ {+ type: "datetime",+ operator: ">=",+ column: "timestamp",+ value: new Date(defaultFromTime),+ },+ {+ type: "datetime",+ operator: "<=",+ column: "timestamp",+ value: new Date(defaultToTime),+ },+ ]);++ // 2. Define the equivalent query for the query builder+ const queryBuilderQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: {+ granularity: "hour",+ },+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // 3. Get result using the query builder+ const queryBuilderResult = await executeQuery(+ projectId,+ queryBuilderQuery,+ );++ // 4. Verify both results+ // Both results should be between 70 and 80 rows+ expect(legacyResult.length).toBeGreaterThanOrEqual(70);+ expect(legacyResult.length).toBeLessThanOrEqual(80);+ expect(queryBuilderResult.length).toBeGreaterThanOrEqual(70);+ expect(queryBuilderResult.length).toBeLessThanOrEqual(80);++ // Compare the non-zero results to each other. The legacy setup should have more empty records in the future+ // so the indexing should match up.+ legacyResult.forEach((result, index) => {+ if (result.countTraceId > 0) {+ const queryBuilderRow = queryBuilderResult[index];+ expect(queryBuilderRow).toBeDefined();+ expect(Number(queryBuilderRow.count_count)).toBe(result.countTraceId);+ }+ });+ });+ });+});diff --git a/web/src/__tests__/queryBuilderSQLI.servertest.ts b/web/src/__tests__/queryBuilderSQLI.servertest.tsnew file mode 100644index 0000000000..88bf2e2c6b--- /dev/null+++ b/web/src/__tests__/queryBuilderSQLI.servertest.ts@@ -0,0 +1,458 @@+import { randomUUID } from "crypto";+import { QueryBuilder } from "@/src/features/query/server/queryBuilder";+import { type QueryType } from "@/src/features/query/types";+import { TRPCError } from "@trpc/server";+import { executeQuery } from "@/src/features/dashboard/server/dashboard-router";++/**+ * Test suite for testing SQL injection vulnerabilities in the QueryBuilder+ */+describe("QueryBuilder SQL Injection Tests", () => {+ // Single project ID for all tests+ const projectId = randomUUID();++ // Time references+ const now = new Date();+ const threeDaysAgo = new Date(now.getTime() - 3 * 24 * 3600000);++ // Time ranges for queries - converted to ClickHouse DateTime format+ const defaultFromTime = threeDaysAgo.toISOString();+ const defaultToTime = now.toISOString();++ // Create a mock ClickHouse client for testing+ const mockClickhouseClient = {+ query: jest.fn().mockImplementation(({ query, query_params }) => {+ // Return the query and params for inspection in tests+ return Promise.resolve({+ json: jest.fn().mockReturnValue({+ data: [],+ query,+ params: query_params,+ }),+ });+ }),+ };++ // Helper function to build a query without executing it+ const buildQueryWithoutExecuting = (query: QueryType, projectId: string) => {+ const queryBuilder = new QueryBuilder(mockClickhouseClient as any);+ return queryBuilder.build(query, projectId);+ };++ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe("SQL Injection via View Parameter", () => {+ it("should prevent injection via invalid view name", async () => {+ // Comment: The view property is restricted to specific enum values,+ // but a determined attacker might try to bypass zod validation or+ // supply a maliciously crafted view name+ const maliciousQuery = {+ view: "traces; DROP TABLE users" as any,+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ };++ // Should throw an error rather than allow the injection+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid query");+ });+ });++ describe("SQL Injection via Dimension Fields", () => {+ it("should prevent injection via dimension field name", async () => {+ // Comment: The field names in dimensions should be validated against allowed fields+ // in the view declaration. This test checks if an attacker can inject arbitrary SQL+ // by manipulating the dimension field name.+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "name; DROP TABLE traces; --" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should throw an error for invalid dimension+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid dimension");+ });++ it("should safely handle special characters in valid dimension fields", async () => {+ // Comment: Even with valid fields, we need to ensure special characters+ // don't lead to injections when building the SQL query+ const query: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }], // Valid field+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "name",+ operator: "=",+ value: "chat'; DROP TABLE traces; --", // SQL injection in value+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should build a valid query using parameterized queries for safety+ const result = buildQueryWithoutExecuting(query, projectId);++ // Ensure the value is parameterized and not directly included in the SQL+ expect(result.query).not.toContain("chat'; DROP TABLE traces; --");+ expect(Object.values(result.parameters)).toContain(+ "chat'; DROP TABLE traces; --",+ );+ });+ });++ describe("SQL Injection via Metrics", () => {+ it("should prevent injection via metric measure name", async () => {+ // Comment: Similar to dimensions, metrics should be validated against allowed measures+ // This test checks if an attacker can inject SQL via the measure property+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [+ {+ measure: "count); DROP TABLE traces; --",+ aggregation: "count",+ },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should throw an error for invalid metric+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid metric");+ });++ it("should prevent injection via metric aggregation", async () => {+ // Comment: The aggregation function could be another injection vector if+ // not properly validated+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [+ {+ measure: "count",+ aggregation: "count); DROP TABLE traces; --" as any,+ },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should throw an error for invalid aggregation+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid query");+ });+ });++ describe("SQL Injection via Filters", () => {+ it("should prevent injection via filter field name", async () => {+ // Comment: Filter field names must be validated like dimensions+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "environment); DROP TABLE traces; --",+ operator: "=",+ value: "production",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should throw an error for invalid filter field+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid filter");+ });++ it("should prevent injection via filter operator", async () => {+ // Comment: Filter operators should be validated against a list of allowed operators+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "environment",+ operator: "=; DROP TABLE traces; --" as any,+ value: "production",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should throw an error for invalid operator+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid query");+ });++ it("should safely handle special characters in filter values", async () => {+ // Comment: Filter values should be parameterized to prevent injection+ const query: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "environment",+ operator: "=",+ type: "string",+ value: "production'; DROP TABLE traces; --",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should build a valid query with parameterization+ const result = buildQueryWithoutExecuting(query, projectId);++ // Check for parameterization+ expect(result.query).not.toContain("production'; DROP TABLE traces; --");+ expect(Object.values(result.parameters)).toContain(+ "production'; DROP TABLE traces; --",+ );+ });++ it("should safely handle array values in IN operators", async () => {+ // Comment: IN operators with arrays need special handling for SQL injection prevention+ const query: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [+ {+ column: "environment",+ operator: "any of",+ value: ["production", "development'); DROP TABLE traces; --"],+ type: "stringOptions",+ },+ ],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Should parameterize the values+ const result = buildQueryWithoutExecuting(query, projectId);++ expect(result.query).not.toContain(+ "production,development'); DROP TABLE traces; --",+ );+ });+ });++ describe("SQL Injection via Time Dimension", () => {+ it("should prevent injection via time dimension granularity", async () => {+ // Comment: Time dimension granularity should be validated against allowed values+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: {+ granularity: "minute; DROP TABLE traces; --" as any,+ },+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };+ // Should throw an error for invalid granularity+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid query");+ });+ });++ describe("SQL Injection via Timestamp Parameters", () => {+ it("should safely handle malicious timestamp strings", async () => {+ // Comment: Timestamps need to be properly validated and converted+ // to prevent SQL injection+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2023-01-01'); DROP TABLE traces; --",+ toTimestamp: defaultToTime,+ orderBy: null,+ };+ // Should throw an error for invalid timestamp format+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid query");+ });+ });++ describe("SQL Injection via Project ID", () => {+ it("should safely handle malicious project ID", async () => {+ // Comment: Project ID is a critical parameter that must be properly sanitized+ const query: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ const maliciousProjectId = "fake-id'; DROP TABLE traces; --";++ // Should parameterize the project ID+ const result = buildQueryWithoutExecuting(query, maliciousProjectId);++ // Check for parameterization+ expect(result.query).not.toContain(maliciousProjectId);+ expect(Object.values(result.parameters)).toContain(maliciousProjectId);+ });+ });++ describe("SQL Injection via OrderBy Parameters", () => {+ it("should prevent injection via orderBy field name", async () => {+ // Comment: The field names in orderBy should be validated against dimension and metric fields+ // to prevent SQL injection via field name+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: [+ {+ field: "name; DROP TABLE traces; --",+ direction: "asc",+ },+ ],+ };++ // Should throw an error for invalid orderBy field+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid orderBy field");+ });++ it("should prevent injection via orderBy direction", async () => {+ // Comment: The direction value should be validated to prevent SQL injection+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: [+ {+ field: "name",+ direction: "asc; DROP TABLE traces; --" as any,+ },+ ],+ };++ // Should throw an error for invalid direction+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid query");+ });++ it("should prevent injection via non-existing metric field in orderBy", async () => {+ // Comment: The field must exist as a metric with proper aggregation prefix+ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: [+ {+ field: "sum_malicious_metric; DROP TABLE traces; --",+ direction: "asc",+ },+ ],+ };++ // Should throw an error for invalid orderBy field+ expect(() =>+ buildQueryWithoutExecuting(maliciousQuery, projectId),+ ).toThrow("Invalid orderBy field");+ });+ });++ describe("Integration with executeQuery function", () => {+ it("should safely handle malicious query parameters through executeQuery", async () => {+ // Comment: This tests the integration with the dashboard router's executeQuery function+ // to ensure SQL injection protection works end-to-end+ jest.spyOn(console, "error").mockImplementation(() => {});++ const maliciousQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [+ {+ measure: "count); DELETE FROM traces; --" as any,+ aggregation: "count",+ },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: defaultFromTime,+ toTimestamp: defaultToTime,+ orderBy: null,+ };++ // Expect the executeQuery function to throw a TRPC error+ // rather than allowing the injection+ await expect(executeQuery(projectId, maliciousQuery)).rejects.toThrow(+ TRPCError,+ );+ });+ });+});diff --git a/web/src/features/dashboard/components/TracesBarListChart.tsx b/web/src/features/dashboard/components/TracesBarListChart.tsxindex 8a54ec930b..7464e712b6 100644--- a/web/src/features/dashboard/components/TracesBarListChart.tsx+++ b/web/src/features/dashboard/components/TracesBarListChart.tsx@@ -7,30 +7,44 @@ import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";import { BarList } from "@tremor/react";import { compactNumberFormatter } from "@/src/utils/numbers";import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import {+ type QueryType,+ mapLegacyUiTableFilterToView,+} from "@/src/features/query";export const TracesBarListChart = ({className,projectId,globalFilterState,+ fromTimestamp,+ toTimestamp,isLoading = false,}: {className?: string;projectId: string;globalFilterState: FilterState;+ fromTimestamp: Date;+ toTimestamp: Date;isLoading?: boolean;}) => {const [isExpanded, setIsExpanded] = useState(false);- const timeFilter = globalFilterState.map((f) =>- f.type === "datetime" ? { ...f, column: "timestamp" } : f,- );- const totalTraces = api.dashboard.chart.useQuery(+ // Total traces query using executeQuery+ const totalTracesQuery: QueryType = {+ view: "traces",+ dimensions: [],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: mapLegacyUiTableFilterToView("traces", globalFilterState),+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };++ const totalTraces = api.dashboard.executeQuery.useQuery({projectId,- from: "traces",- select: [{ column: "traceId", agg: "COUNT" }],- filter: timeFilter,- queryName: "traces-total",+ query: totalTracesQuery,},{trpc: {@@ -42,15 +56,22 @@ export const TracesBarListChart = ({},);- const traces = api.dashboard.chart.useQuery(+ // Traces grouped by name query using executeQuery+ const tracesQuery: QueryType = {+ view: "traces",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "count", aggregation: "count" }],+ filters: mapLegacyUiTableFilterToView("traces", globalFilterState),+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };++ const traces = api.dashboard.executeQuery.useQuery({projectId,- from: "traces",- select: [{ column: "traceId", agg: "COUNT" }, { column: "traceName" }],- filter: timeFilter,- groupBy: [{ column: "traceName", type: "string" }],- orderBy: [{ column: "traceId", direction: "DESC", agg: "COUNT" }],- queryName: "traces-grouped-by-name",+ query: tracesQuery,},{trpc: {@@ -62,14 +83,14 @@ export const TracesBarListChart = ({},);- const transformedTraces = traces.data- ? traces.data.map((item) => {- return {- name: item.traceName ? (item.traceName as string) : "Unknown",- value: item.countTraceId as number,- };- })- : [];+ // Transform the data to match the expected format for the BarList+ const transformedTraces =+ traces.data?.map((item: any) => {+ return {+ name: item.name ? (item.name as string) : "Unknown",+ value: Number(item.count_count),+ };+ }) ?? [];const maxNumberOfEntries = { collapsed: 5, expanded: 20 };@@ -87,7 +108,9 @@ export const TracesBarListChart = ({<><TotalMetricmetric={compactNumberFormatter(- totalTraces.data?.[0]?.countTraceId as number,+ totalTraces.data?.[0]?.count_count+ ? Number(totalTraces.data[0].count_count)+ : 0,)}description={"Total traces tracked"}/>diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 8491cce068..ffe7ba7a16 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -33,6 +33,12 @@ import {} from "@langfuse/shared/src/server";import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";import { dashboardColumnDefinitions } from "@langfuse/shared";+import { QueryBuilder } from "@/src/features/query/server/queryBuilder";+import {+ type QueryType,+ query as customQuery,+} from "@/src/features/query/types";+import { clickhouseClient } from "@langfuse/shared/src/server";export const dashboardRouter = createTRPCRouter({chart: protectedProjectProcedure@@ -271,6 +277,16 @@ export const dashboardRouter = createTRPCRouter({);return createHistogramData(data);}),+ executeQuery: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ query: customQuery,+ }),+ )+ .query(async ({ input }) => {+ return executeQuery(input.projectId, input.query as QueryType);+ }),});const extractTimeSeries = (groupBy?: z.infer<typeof groupByInterface>) => {@@ -281,3 +297,49 @@ const extractTimeSeries = (groupBy?: z.infer<typeof groupByInterface>) => {});return temporal?.type === "datetime" ? temporal.temporalUnit : undefined;};++/**+ * Execute a query using the QueryBuilder.+ *+ * @param projectId - The project ID+ * @param query - The query configuration as defined in QueryType+ * @returns The query result data+ */+export async function executeQuery(+ projectId: string,+ query: QueryType,+): Promise<Array<Record<string, unknown>>> {+ try {+ // Initialize query builder with ClickHouse client+ const queryBuilder = new QueryBuilder();++ // Build the query+ const { query: compiledQuery, parameters } = queryBuilder.build(+ query,+ projectId,+ );++ // Execute the query+ const result = await clickhouseClient({+ tags: {+ feature: "custom-queries",+ type: query.view,+ kind: "analytic",+ projectId,+ },+ }).query({+ query: compiledQuery,+ query_params: parameters,+ });++ // Return the result+ return (await result.json<Record<string, unknown>>()).data;+ } catch (error) {+ logger.error("Error executing query", { error, projectId, query });+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to execute query",+ cause: error,+ });+ }+}diff --git a/web/src/features/query/dashboardUiTableToViewMapping.ts b/web/src/features/query/dashboardUiTableToViewMapping.tsnew file mode 100644index 0000000000..ca19382f77--- /dev/null+++ b/web/src/features/query/dashboardUiTableToViewMapping.ts@@ -0,0 +1,98 @@+import { z } from "zod";+import { dashboardColumnDefinitions, singleFilter } from "@langfuse/shared";+import { type views } from "@/src/features/query/types";++const FilterArray = z.array(singleFilter);++const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {+ traces: [+ {+ uiTableName: "Trace Name",+ viewName: "name",+ },+ {+ uiTableName: "User",+ viewName: "user_id",+ },+ {+ uiTableName: "Release",+ viewName: "release",+ },+ {+ uiTableName: "Version",+ viewName: "version",+ },+ ],+ observations: [+ {+ uiTableName: "Trace Name",+ viewName: "traceName",+ },+ {+ uiTableName: "Type",+ viewName: "type",+ },+ {+ uiTableName: "Model",+ viewName: "providedModelName",+ },+ ],+ "scores-numeric": [+ {+ uiTableName: "Score Name",+ viewName: "name",+ },+ {+ uiTableName: "Score Source",+ viewName: "source",+ },+ {+ uiTableName: "Scores Data Type",+ viewName: "dataType",+ },+ ],+ "scores-categorical": [+ {+ uiTableName: "Score Name",+ viewName: "name",+ },+ {+ uiTableName: "Score Source",+ viewName: "source",+ },+ {+ uiTableName: "Scores Data Type",+ viewName: "dataType",+ },+ ],+};++const isLegacyUiTableFilter = (+ filter: z.infer<typeof singleFilter>,+): boolean => {+ return dashboardColumnDefinitions.some(+ (columnDef) => columnDef.uiTableName === filter.column,+ );+};++export const mapLegacyUiTableFilterToView = (+ view: z.infer<typeof views>,+ filters: z.infer<typeof FilterArray>,+): z.infer<typeof FilterArray> => {+ return filters.flatMap((filter) => {+ // If it's not a legacy filter, return it as is+ if (!isLegacyUiTableFilter(filter)) {+ return [filter];+ }+ // Check if we have a match in our mapping+ const definition = viewMappings[view].find(+ (def) => def.uiTableName === filter.column,+ );+ // Ignore if there is no match+ if (!definition) {+ return [];+ }+ // Overwrite column name if a match is found+ return [{ ...filter, column: definition.viewName }];+ });+};diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.tsnew file mode 100644index 0000000000..c761df4142--- /dev/null+++ b/web/src/features/query/dataModel.ts@@ -0,0 +1,374 @@+import { type z } from "zod";+import {+ type views,+ type ViewDeclarationType,+ type DimensionsDeclarationType,+} from "@/src/features/query/types";++// The data model defines all available dimensions, measures, and the timeDimension for a given view.+// Make sure to update ./dashboardUiTableToViewMapping.ts if you make changes++export const traceView: ViewDeclarationType = {+ name: "traces",+ dimensions: {+ id: {+ sql: "id",+ type: "string",+ },+ name: {+ sql: "name",+ type: "string",+ },+ userId: {+ sql: "user_id",+ type: "string",+ },+ sessionId: {+ sql: "session_id",+ type: "string",+ },+ release: {+ sql: "release",+ type: "string",+ },+ version: {+ sql: "version",+ type: "string",+ },+ environment: {+ sql: "environment",+ type: "string",+ },+ },+ measures: {+ count: {+ sql: "count(*)",+ alias: "count",+ type: "count",+ },+ observationsCount: {+ sql: "uniq(observations.id)",+ alias: "observations_count",+ type: "count",+ relationTable: "observations",+ },+ scoresCount: {+ sql: "uniq(scores.id)",+ alias: "scores_count",+ type: "count",+ relationTable: "scores",+ },+ latency: {+ sql: "date_diff('millisecond', min(observations.start_time), max(observations.end_time))",+ alias: "latency",+ type: "number",+ relationTable: "observations",+ },+ },+ tableRelations: {+ observations: {+ name: "observations",+ joinConditionSql:+ "ON traces.id = observations.trace_id AND traces.project_id = observations.project_id",+ timeDimension: "start_time",+ },+ scores: {+ name: "scores",+ joinConditionSql:+ "ON traces.id = scores.trace_id AND traces.project_id = scores.project_id",+ timeDimension: "timestamp",+ },+ },+ segments: [],+ timeDimension: "timestamp",+ baseCte: `traces FINAL`,+};++export const observationsView: ViewDeclarationType = {+ name: "observations",+ dimensions: {+ id: {+ sql: "id",+ type: "string",+ },+ traceId: {+ sql: "trace_id",+ type: "string",+ },+ traceName: {+ sql: "name",+ alias: "trace_name",+ type: "string",+ relationTable: "traces",+ },+ environment: {+ sql: "environment",+ type: "string",+ },+ parentObservationId: {+ sql: "parent_observation_id",+ type: "string",+ },+ type: {+ sql: "type",+ type: "string",+ },+ name: {+ sql: "name",+ type: "string",+ },+ level: {+ sql: "level",+ type: "string",+ },+ version: {+ sql: "version",+ type: "string",+ },+ providedModelName: {+ sql: "provided_model_name",+ type: "string",+ },+ promptName: {+ sql: "prompt_name",+ type: "string",+ },+ promptVersion: {+ sql: "prompt_version",+ type: "string",+ },+ userId: {+ sql: "user_id",+ type: "string",+ relationTable: "traces",+ },+ sessionId: {+ sql: "session_id",+ type: "string",+ relationTable: "traces",+ },+ },+ measures: {+ count: {+ sql: "count(*)",+ alias: "count",+ type: "count",+ },+ latency: {+ sql: "date_diff('millisecond', any(observations.start_time), any(observations.end_time))",+ alias: "latency",+ type: "number",+ },+ totalTokens: {+ sql: "sumMap(usage_details)['total']",+ alias: "total_tokens",+ type: "sum",+ },+ totalCost: {+ sql: "sum(total_cost)",+ alias: "total_cost",+ type: "sum",+ },+ timeToFirstToken: {+ sql: "date_diff('millisecond', any(observations.start_time), any(observations.completion_start_time))",+ alias: "time_to_first_token",+ type: "number",+ },+ countScores: {+ sql: "uniq(scores.id)",+ alias: "count_scores",+ type: "count",+ relationTable: "scores",+ },+ },+ tableRelations: {+ traces: {+ name: "traces",+ joinConditionSql:+ "ON observations.trace_id = traces.id AND observations.project_id = traces.project_id",+ timeDimension: "timestamp",+ },+ scores: {+ name: "scores",+ joinConditionSql:+ "ON observations.id = scores.observation_id AND observations.project_id = scores.project_id",+ timeDimension: "timestamp",+ },+ },+ segments: [],+ timeDimension: "start_time",+ baseCte: `observations FINAL`,+};++const scoreBaseDimensions: DimensionsDeclarationType = {+ id: {+ sql: "id",+ type: "string",+ },+ environment: {+ sql: "environment",+ type: "string",+ },+ name: {+ sql: "name",+ type: "string",+ },+ source: {+ sql: "source",+ type: "string",+ },+ dataType: {+ sql: "data_type",+ type: "string",+ },+ traceId: {+ sql: "trace_id",+ type: "string",+ },+ traceName: {+ sql: "name",+ alias: "trace_name",+ type: "string",+ relationTable: "traces",+ },+ userId: {+ sql: "user_id",+ alias: "user_id",+ type: "string",+ relationTable: "traces",+ },+ sessionId: {+ sql: "session_id",+ alias: "session_id",+ type: "string",+ relationTable: "traces",+ },+ observationId: {+ sql: "observation_id",+ type: "string",+ },+ observationName: {+ sql: "name",+ alias: "observation_name",+ type: "string",+ relationTable: "observations",+ },+ observationModelName: {+ sql: "provided_model_name",+ alias: "observation_model_name",+ type: "string",+ relationTable: "observations",+ },+ observationPromptName: {+ sql: "prompt_name",+ alias: "observation_prompt_name",+ type: "string",+ relationTable: "observations",+ },+ observationPromptVersion: {+ sql: "prompt_version",+ alias: "observation_prompt_version",+ type: "string",+ relationTable: "observations",+ },+ configId: {+ sql: "config_id",+ type: "string",+ },+};++export const scoresNumericView: ViewDeclarationType = {+ name: "scores_numeric",+ dimensions: {+ ...scoreBaseDimensions,+ },+ measures: {+ count: {+ sql: "count(*)",+ alias: "count",+ type: "count",+ },+ value: {+ sql: "any(value)",+ alias: "value",+ type: "number",+ },+ },+ tableRelations: {+ traces: {+ name: "traces",+ joinConditionSql:+ "ON scores.trace_id = traces.id AND scores.project_id = traces.project_id",+ timeDimension: "timestamp",+ },+ observations: {+ name: "observations",+ joinConditionSql:+ "ON scores.observation_id = observations.id AND scores.project_id = observations.project_id",+ timeDimension: "start_time",+ },+ },+ segments: [+ {+ column: "data_type",+ operator: "=",+ value: "NUMERIC",+ type: "string",+ },+ ],+ timeDimension: "timestamp",+ baseCte: `scores scores_numeric FINAL`,+};++export const scoresCategoricalView: ViewDeclarationType = {+ name: "scores_categorical",+ dimensions: {+ ...scoreBaseDimensions,+ stringValue: {+ sql: "string_value",+ type: "string",+ },+ },+ measures: {+ count: {+ sql: "count(*)",+ alias: "count",+ type: "count",+ },+ },+ tableRelations: {+ traces: {+ name: "traces",+ joinConditionSql:+ "ON scores.trace_id = traces.id AND scores.project_id = traces.project_id",+ timeDimension: "timestamp",+ },+ observations: {+ name: "observations",+ joinConditionSql:+ "ON scores.observation_id = observations.id AND scores.project_id = observations.project_id",+ timeDimension: "start_time",+ },+ },+ segments: [+ {+ column: "data_type",+ // Here, we want to include everything that is not numeric.+ operator: "does not contain",+ value: "NUMERIC",+ type: "string",+ },+ ],+ timeDimension: "timestamp",+ baseCte: `scores scores_categorical FINAL`,+};++export const viewDeclarations: Record<+ z.infer<typeof views>,+ ViewDeclarationType+> = {+ traces: traceView,+ observations: observationsView,+ "scores-numeric": scoresNumericView,+ "scores-categorical": scoresCategoricalView,+};diff --git a/web/src/features/query/index.ts b/web/src/features/query/index.tsnew file mode 100644index 0000000000..5555f1f257--- /dev/null+++ b/web/src/features/query/index.ts@@ -0,0 +1,3 @@+export * from "./dataModel";+export * from "./dashboardUiTableToViewMapping";+export * from "./types";diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsnew file mode 100644index 0000000000..6c50c0030b--- /dev/null+++ b/web/src/features/query/server/queryBuilder.ts@@ -0,0 +1,805 @@+import { type z } from "zod";+import { convertDateToClickhouseDateTime } from "@langfuse/shared/src/server";+import {+ type QueryType,+ type ViewDeclarationType,+ type views,+ query as queryModel,+ type metricAggregations,+ type granularities,+} from "../types";+import { viewDeclarations } from "@/src/features/query/dataModel";+import {+ FilterList,+ createFilterFromFilterState,+} from "@langfuse/shared/src/server";++type AppliedDimensionType = {+ table: string;+ sql: string;+ alias?: string;+ relationTable?: string;+};++type AppliedMetricType = {+ sql: string;+ aggregation: z.infer<typeof metricAggregations>;+ alias?: string;+ relationTable?: string;+};++export class QueryBuilder {+ private translateAggregation(+ aggregation: z.infer<typeof metricAggregations>,+ ): string {+ switch (aggregation) {+ case "sum":+ return "sum";+ case "avg":+ return "avg";+ case "count":+ return "count";+ case "max":+ return "max";+ case "min":+ return "min";+ case "p50":+ return "quantile(0.5)";+ case "p75":+ return "quantile(0.75)";+ case "p90":+ return "quantile(0.9)";+ case "p95":+ return "quantile(0.95)";+ case "p99":+ return "quantile(0.99)";+ default:+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const exhaustiveCheck: never = aggregation;+ throw new Error(`Invalid aggregation: ${aggregation}`);+ }+ }++ private getViewDeclaration(+ viewName: z.infer<typeof views>,+ ): ViewDeclarationType {+ if (!(viewName in viewDeclarations)) {+ throw new Error(+ `Invalid view. Must be one of ${Object.keys(viewDeclarations)}`,+ );+ }+ return viewDeclarations[viewName];+ }++ private mapDimensions(+ dimensions: Array<{ field: string }>,+ view: ViewDeclarationType,+ ): AppliedDimensionType[] {+ return dimensions.map((dimension) => {+ if (!(dimension.field in view.dimensions)) {+ throw new Error(+ `Invalid dimension. Must be one of ${Object.keys(view.dimensions)}`,+ );+ }+ const dim = view.dimensions[dimension.field];+ return { ...dim, table: dim.relationTable || view.name };+ });+ }++ private mapMetrics(+ metrics: Array<{+ measure: string;+ aggregation: z.infer<typeof metricAggregations>;+ }>,+ view: ViewDeclarationType,+ ): AppliedMetricType[] {+ return metrics.map((metric) => {+ if (!(metric.measure in view.measures)) {+ throw new Error(+ `Invalid metric. Must be one of ${Object.keys(view.measures)}`,+ );+ }+ return {+ ...view.measures[metric.measure],+ aggregation: metric.aggregation,+ };+ });+ }++ private mapFilters(+ filters: z.infer<typeof queryModel>["filters"],+ view: ViewDeclarationType,+ ) {+ // Transform our filters to match the column mapping format expected by createFilterFromFilterState+ const columnMappings = filters.map((filter) => {+ let clickhouseSelect: string;+ let clickhouseTableName: string = view.name;+ let type: string;++ if (filter.column in view.dimensions) {+ const dimension = view.dimensions[filter.column];+ clickhouseSelect = dimension.sql;+ type = dimension.type;+ } else if (filter.column in view.measures) {+ const measure = view.measures[filter.column];+ clickhouseSelect = measure.sql;+ type = measure.type;+ } else if (filter.column === view.timeDimension) {+ clickhouseSelect = view.timeDimension;+ type = "datetime";+ } else {+ throw new Error(+ `Invalid filter column. Must be one of ${Object.keys(view.dimensions)} or ${Object.keys(view.measures)} or ${view.timeDimension}`,+ );+ }++ return {+ uiTableName: filter.column,+ uiTableId: filter.column,+ clickhouseTableName,+ clickhouseSelect,+ queryPrefix: view.name,+ type,+ };+ });++ // Use the createFilterFromFilterState function to create proper Clickhouse filters+ return createFilterFromFilterState(filters, columnMappings);+ }++ private addStandardFilters(+ filterList: FilterList,+ view: ViewDeclarationType,+ projectId: string,+ fromTimestamp: string,+ toTimestamp: string,+ ) {+ // Create column mappings for standard filters+ const projectIdMapping = {+ uiTableName: "project_id",+ uiTableId: "project_id",+ clickhouseTableName: view.name,+ clickhouseSelect: "project_id",+ queryPrefix: view.name,+ type: "string",+ };++ const timeDimensionMapping = {+ uiTableName: view.timeDimension,+ uiTableId: view.timeDimension,+ clickhouseTableName: view.name,+ clickhouseSelect: view.timeDimension,+ queryPrefix: view.name,+ type: "datetime",+ };++ // Add project_id filter+ const projectIdFilter = createFilterFromFilterState(+ [+ {+ column: "project_id",+ operator: "=",+ value: projectId,+ type: "string",+ },+ ],+ [projectIdMapping],+ );++ // Add fromTimestamp filter+ const fromFilter = createFilterFromFilterState(+ [+ {+ column: view.timeDimension,+ operator: ">=",+ value: new Date(fromTimestamp),+ type: "datetime",+ },+ ],+ [timeDimensionMapping],+ );++ // Add toTimestamp filter+ const toFilter = createFilterFromFilterState(+ [+ {+ column: view.timeDimension,+ operator: "<=",+ value: new Date(toTimestamp),+ type: "datetime",+ },+ ],+ [timeDimensionMapping],+ );++ // Add all filters to the filter list+ filterList.push(...projectIdFilter, ...fromFilter, ...toFilter);++ // Add segment filters if any+ if (view.segments.length > 0) {+ // Create column mappings for segment filters+ const segmentsMappings = view.segments.map((segment) => ({+ uiTableName: segment.column,+ uiTableId: segment.column,+ clickhouseTableName: view.name,+ clickhouseSelect: segment.column,+ queryPrefix: view.name,+ type: segment.type,+ }));++ const segmentFilters = createFilterFromFilterState(+ view.segments,+ segmentsMappings,+ );+ filterList.push(...segmentFilters);+ }++ return filterList;+ }++ private collectRelationTables(+ appliedDimensions: AppliedDimensionType[],+ appliedMetrics: AppliedMetricType[],+ ) {+ const relationTables = new Set<string>();+ appliedDimensions.forEach((dimension) => {+ if (dimension.relationTable) {+ relationTables.add(dimension.relationTable);+ }+ });+ appliedMetrics.forEach((metric) => {+ if (metric.relationTable) {+ relationTables.add(metric.relationTable);+ }+ });+ return relationTables;+ }++ private buildJoins(+ relationTables: Set<string>,+ view: ViewDeclarationType,+ filterList: FilterList,+ query: QueryType,+ ) {+ const relationJoins = [];+ for (const relationTableName of relationTables) {+ if (!(relationTableName in view.tableRelations)) {+ throw new Error(+ `Invalid relationTable: ${relationTableName}. Must be one of ${Object.keys(view.tableRelations)}`,+ );+ }++ const relation = view.tableRelations[relationTableName];+ let joinStatement = `LEFT JOIN ${relation.name} FINAL ${relation.joinConditionSql}`;++ // Create time dimension mapping for the relation table+ const relationTimeDimensionMapping = {+ uiTableName: relation.timeDimension,+ uiTableId: relation.timeDimension,+ clickhouseTableName: relation.name,+ clickhouseSelect: relation.timeDimension,+ queryPrefix: relation.name,+ type: "datetime",+ };++ // Add relation-specific timestamp filters+ const fromFilter = createFilterFromFilterState(+ [+ {+ column: relation.timeDimension,+ operator: ">=",+ value: new Date(query.fromTimestamp),+ type: "datetime",+ },+ ],+ [relationTimeDimensionMapping],+ );++ const toFilter = createFilterFromFilterState(+ [+ {+ column: relation.timeDimension,+ operator: "<=",+ value: new Date(query.toTimestamp),+ type: "datetime",+ },+ ],+ [relationTimeDimensionMapping],+ );++ // Add filters to the filter list+ filterList.push(...fromFilter, ...toFilter);++ relationJoins.push(joinStatement);+ }+ return relationJoins;+ }++ private buildWhereClause(+ filterList: FilterList,+ parameters: Record<string, unknown>,+ ) {+ if (filterList.length() === 0) return "";++ // Use the FilterList's apply method to get the query and parameters+ const { query, params } = filterList.apply();++ // Add all parameters to the main parameters object+ Object.assign(parameters, params);++ // Return the WHERE clause with the query+ return ` WHERE ${query}`;+ }++ private determineTimeGranularity(+ fromTimestamp: string,+ toTimestamp: string,+ ): z.infer<typeof granularities> {+ const from = new Date(fromTimestamp);+ const to = new Date(toTimestamp);+ const diffMs = to.getTime() - from.getTime();+ const diffHours = diffMs / (1000 * 60 * 60);++ // Choose appropriate granularity based on date range to get ~50 buckets+ if (diffHours < 2) {+ return "minute"; // Less than a 2h, use minutes+ } else if (diffHours < 72) {+ return "hour"; // Less than 3 days, use hours+ } else if (diffHours < 1440) {+ return "day"; // Less than 60 days, use days+ } else if (diffHours < 8760) {+ return "week"; // Less than a year, use weeks+ } else {+ return "month"; // Over a year, use months+ }+ }++ private getTimeDimensionSql(+ sql: string,+ granularity: z.infer<typeof granularities>,+ ): string {+ switch (granularity) {+ case "minute":+ return `toStartOfMinute(${sql})`;+ case "hour":+ return `toStartOfHour(${sql})`;+ case "day":+ return `toDate(${sql})`;+ case "week":+ return `toMonday(${sql})`;+ case "month":+ return `toStartOfMonth(${sql})`;+ case "auto":+ throw new Error(+ `Granularity 'auto' is not supported for getTimeDimensionSql`,+ );+ default:+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const exhaustiveCheck: never = granularity;+ throw new Error(+ `Invalid time granularity: ${granularity}. Must be one of minute, hour, day, week, month`,+ );+ }+ }++ private buildInnerDimensionsPart(+ appliedDimensions: AppliedDimensionType[],+ query: QueryType,+ view: ViewDeclarationType,+ ) {+ let dimensions = "";++ // Add regular dimensions+ if (appliedDimensions.length > 0) {+ dimensions += `${appliedDimensions+ .map(+ (dimension) =>+ `any(${dimension.table}.${dimension.sql}) as ${dimension.alias ?? dimension.sql}`,+ )+ .join(",\n")},`;+ }++ // Add time dimension if specified+ if (query.timeDimension) {+ const granularity =+ query.timeDimension.granularity === "auto"+ ? this.determineTimeGranularity(+ query.fromTimestamp,+ query.toTimestamp,+ )+ : query.timeDimension.granularity;++ const timeDimensionSql = this.getTimeDimensionSql(+ `${view.name}.${view.timeDimension}`,+ granularity,+ );+ dimensions += `any(${timeDimensionSql}) as time_dimension,`;+ }++ return dimensions;+ }++ private buildInnerMetricsPart(appliedMetrics: AppliedMetricType[]) {+ return appliedMetrics.length > 0+ ? `${appliedMetrics.map((metric) => `${metric.sql} as ${metric.alias || metric.sql}`).join(",\n")}`+ : "count(*) as count";+ }++ private buildInnerSelect(+ view: ViewDeclarationType,+ innerDimensionsPart: string,+ innerMetricsPart: string,+ fromClause: string,+ ) {+ return `+ SELECT+ ${view.name}.project_id,+ ${view.name}.id,+ ${innerDimensionsPart}+ ${innerMetricsPart}+ ${fromClause}+ GROUP BY ${view.name}.project_id, ${view.name}.id`;+ }++ private buildOuterDimensionsPart(+ appliedDimensions: AppliedDimensionType[],+ hasTimeDimension: boolean,+ ) {+ let dimensions = "";++ // Add regular dimensions+ if (appliedDimensions.length > 0) {+ dimensions += `${appliedDimensions+ .map(+ (dimension) =>+ `${dimension.alias ?? dimension.sql} as ${dimension.alias || dimension.sql}`,+ )+ .join(",\n")},`;+ }++ // Add time dimension if it exists+ if (hasTimeDimension) {+ dimensions += `time_dimension,`;+ }++ return dimensions;+ }++ private buildOuterMetricsPart(appliedMetrics: AppliedMetricType[]) {+ return appliedMetrics.length > 0+ ? `${appliedMetrics.map((metric) => `${this.translateAggregation(metric.aggregation)}(${metric.alias || metric.sql}) as ${metric.aggregation}_${metric.alias || metric.sql}`).join(",\n")}`+ : "count(*) as count";+ }++ private buildGroupByClause(+ appliedDimensions: AppliedDimensionType[],+ hasTimeDimension: boolean,+ ) {+ const dimensions = [];++ // Add regular dimensions+ if (appliedDimensions.length > 0) {+ dimensions.push(+ ...appliedDimensions.map(+ (dimension) => dimension.alias ?? dimension.sql,+ ),+ );+ }++ // Add time dimension if it exists+ if (hasTimeDimension) {+ dimensions.push("time_dimension");+ }++ return dimensions.length > 0 ? `GROUP BY ${dimensions.join(",\n")}` : "";+ }++ /**+ * Builds a WITH FILL clause for time dimension to ensure continuous time series data.+ * This fills in gaps in the time series with zero values based on the granularity.+ * Only applied if timeDimension is used and no ORDER BY is specified.+ */+ private buildWithFillClause(+ timeDimension: {+ granularity: z.infer<typeof granularities>;+ } | null,+ fromTimestamp: string,+ toTimestamp: string,+ orderBy: Array<{ field: string; direction: string }> | null,+ parameters: Record<string, unknown>,+ ): string {+ if (!timeDimension) {+ return "";+ }++ if (orderBy && orderBy.length > 0) {+ return ""; // Skip WITH FILL if ORDER BY is specified+ }++ // Determine granularity for WITH FILL if timeDimension is used+ const granularity =+ timeDimension.granularity === "auto"+ ? this.determineTimeGranularity(fromTimestamp, toTimestamp)+ : timeDimension.granularity;++ // Calculate appropriate STEP for WITH FILL based on granularity+ let step: string;+ switch (granularity) {+ case "minute":+ step = "INTERVAL 1 MINUTE";+ break;+ case "hour":+ step = "INTERVAL 1 HOUR";+ break;+ case "day":+ step = "INTERVAL 1 DAY";+ break;+ case "week":+ step = "INTERVAL 1 WEEK";+ break;+ case "month":+ step = "INTERVAL 1 MONTH";+ break;+ default:+ step = "INTERVAL 1 DAY"; // Default to day if granularity is unknown+ }++ parameters["fillFromDate"] = convertDateToClickhouseDateTime(+ new Date(fromTimestamp),+ );+ parameters["fillToDate"] = convertDateToClickhouseDateTime(+ new Date(toTimestamp),+ );++ return ` WITH FILL FROM ${this.getTimeDimensionSql("{fillFromDate: DateTime64(3)}", granularity)} TO ${this.getTimeDimensionSql("{fillToDate: DateTime64(3)}", granularity)} STEP ${step}`;+ }++ private buildOuterSelect(+ outerDimensionsPart: string,+ outerMetricsPart: string,+ innerQuery: string,+ groupByClause: string,+ orderByClause: string,+ withFillClause: string,+ ) {+ return `+ SELECT+ ${outerDimensionsPart}+ ${outerMetricsPart}+ FROM (${innerQuery})+ ${groupByClause}+ ${orderByClause}+ ${withFillClause}`;+ }++ /**+ * Validates that the provided orderBy fields exist in the dimensions or metrics+ * and returns the processed orderBy array with fully qualified field names.+ */+ private validateAndProcessOrderBy(+ orderBy: Array<{ field: string; direction: string }> | null,+ appliedDimensions: AppliedDimensionType[],+ appliedMetrics: AppliedMetricType[],+ hasTimeDimension: boolean,+ ): Array<{ field: string; direction: string }> {+ if (!orderBy || orderBy.length === 0) {+ // Default order: time dimension if available, otherwise first metric, otherwise first dimension+ if (hasTimeDimension) {+ return [{ field: "time_dimension", direction: "asc" }];+ } else if (appliedMetrics.length > 0) {+ const firstMetric = appliedMetrics[0];+ return [+ {+ field: `${firstMetric.aggregation}_${firstMetric.alias || firstMetric.sql}`,+ direction: "desc",+ },+ ];+ } else if (appliedDimensions.length > 0) {+ const firstDimension = appliedDimensions[0];+ return [+ {+ field: firstDimension.alias || firstDimension.sql,+ direction: "asc",+ },+ ];+ }+ return [];+ }++ // Validate that each orderBy field exists in dimensions or metrics+ return orderBy.map((item) => {+ // Check if the field is a time dimension+ if (hasTimeDimension && item.field === "time_dimension") {+ return item;+ }++ // Check if the field is a dimension+ const matchingDimension = appliedDimensions.find(+ (dim) => dim.alias === item.field || dim.sql === item.field,+ );+ if (matchingDimension) {+ return {+ field: matchingDimension.alias || matchingDimension.sql,+ direction: item.direction,+ };+ }++ // Check if the field is a metric (with aggregation prefix)+ const metricNamePattern =+ /^(sum|avg|count|max|min|p50|p75|p90|p95|p99)_(.+)$/;+ const metricMatch = item.field.match(metricNamePattern);++ if (metricMatch) {+ const [, aggregation, measureName] = metricMatch;+ const matchingMetric = appliedMetrics.find(+ (metric) =>+ (metric.alias === measureName || metric.sql === measureName) &&+ metric.aggregation === aggregation,+ );++ if (matchingMetric) {+ return item;+ }+ }++ throw new Error(+ `Invalid orderBy field: ${item.field}. Must be one of the dimension or metric fields.`,+ );+ });+ }++ /**+ * Builds the ORDER BY clause for the query.+ */+ private buildOrderByClause(+ processedOrderBy: Array<{ field: string; direction: string }>,+ ): string {+ if (processedOrderBy.length === 0) {+ return "";+ }++ return `ORDER BY ${processedOrderBy+ .map((item) => `${item.field} ${item.direction}`)+ .join(", ")}`;+ }++ /**+ * We want to build a ClickHouse query based on the query provided and the viewDeclaration that was selected.+ * The final query should always follow this pattern:+ * ```+ * SELECT+ * <...dimensions>,+ * <...metrics.map(metric => `${metric.aggregation}(${metric.alias})`>+ * FROM (+ * SELECT+ * <baseCte>.project_id,+ * <baseCte>.id+ * <...dimensions.map(dimension => `any(${dimension.sql}) as ${dimension.alias}`>,+ * <...metrics.map(metric => `${metric.sql} as ${metric.alias || metric.sql}`>+ * FROM <baseCte>+ * (...tableRelations.joinConditionSql)+ * WHERE <...filters>+ * GROUP BY <baseCte>.project_id, <baseCte>.id+ * )+ * GROUP BY <...dimensions>+ * ORDER BY <fields with directions>+ * ```+ */+ public build(+ query: QueryType,+ projectId: string,+ ): { query: string; parameters: Record<string, unknown> } {+ // Run zod validation+ const parseResult = queryModel.safeParse(query);+ if (!parseResult.success) {+ throw new Error(+ `Invalid query: ${JSON.stringify(parseResult.error.errors)}`,+ );+ }++ // Initialize parameters object+ const parameters: Record<string, unknown> = {};++ // Get view declaration+ const view = this.getViewDeclaration(query.view);++ // Map dimensions and metrics+ const appliedDimensions = this.mapDimensions(query.dimensions, view);+ const appliedMetrics = this.mapMetrics(query.metrics, view);++ // Create a new FilterList with the mapped filters+ let filterList = new FilterList(this.mapFilters(query.filters, view));++ // Add standard filters (project_id, timestamps)+ filterList = this.addStandardFilters(+ filterList,+ view,+ projectId,+ query.fromTimestamp,+ query.toTimestamp,+ );++ // Build the FROM clause with necessary JOINs+ let fromClause = `FROM ${view.baseCte}`;++ // Handle relation tables+ const relationTables = this.collectRelationTables(+ appliedDimensions,+ appliedMetrics,+ );+ if (relationTables.size > 0) {+ const relationJoins = this.buildJoins(+ relationTables,+ view,+ filterList,+ query,+ );+ fromClause += ` ${relationJoins.join(" ")}`;+ }++ // Build WHERE clause with parameters+ fromClause += this.buildWhereClause(filterList, parameters);++ // Build inner SELECT parts+ const innerDimensionsPart = this.buildInnerDimensionsPart(+ appliedDimensions,+ query,+ view,+ );+ const innerMetricsPart = this.buildInnerMetricsPart(appliedMetrics);++ // Build inner SELECT+ const innerQuery = this.buildInnerSelect(+ view,+ innerDimensionsPart,+ innerMetricsPart,+ fromClause,+ );++ // Build outer SELECT parts+ const outerDimensionsPart = this.buildOuterDimensionsPart(+ appliedDimensions,+ !!query.timeDimension,+ );+ const outerMetricsPart = this.buildOuterMetricsPart(appliedMetrics);+ const groupByClause = this.buildGroupByClause(+ appliedDimensions,+ !!query.timeDimension,+ );++ // Process and validate orderBy fields+ const processedOrderBy = this.validateAndProcessOrderBy(+ query.orderBy,+ appliedDimensions,+ appliedMetrics,+ !!query.timeDimension,+ );++ // Build ORDER BY clause+ const orderByClause = this.buildOrderByClause(processedOrderBy);++ // Build WITH FILL clause for time dimension to fill gaps in timeseries+ const withFillClause = this.buildWithFillClause(+ query.timeDimension,+ query.fromTimestamp,+ query.toTimestamp,+ query.orderBy,+ parameters,+ );++ // Build final query+ const sql = this.buildOuterSelect(+ outerDimensionsPart,+ outerMetricsPart,+ innerQuery,+ groupByClause,+ orderByClause,+ withFillClause,+ );++ return {+ query: sql,+ parameters,+ };+ }+}diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.tsnew file mode 100644index 0000000000..79c54c5d0c--- /dev/null+++ b/web/src/features/query/types.ts@@ -0,0 +1,113 @@+import { z } from "zod";+import { singleFilter } from "@langfuse/shared";++export type ViewDeclarationType = z.infer<typeof viewDeclaration>;+export type DimensionsDeclarationType = z.infer<+ typeof viewDeclaration+>["dimensions"];++export const viewDeclaration = z.object({+ name: z.string(),+ // This is the basic statement that we query from. Usually, this should be the view_name + FINAL or a more complex subquery.+ baseCte: z.string(),+ dimensions: z.record(+ z.object({+ sql: z.string(),+ alias: z.string().optional(),+ type: z.enum(["string", "number", "bool"]),+ relationTable: z.string().optional(),+ }),+ ),+ measures: z.record(+ z.object({+ sql: z.string(),+ alias: z.string().optional(),+ type: z.enum(["count", "sum", "number"]),+ relationTable: z.string().optional(),+ }),+ ),+ tableRelations: z.record(+ z.object({+ name: z.string(),+ joinConditionSql: z.string(),+ timeDimension: z.string(),+ }),+ ),+ // Segments are used to apply "constant" filters to the query. For example, if we only want one type of observations.+ segments: z.array(singleFilter),+ timeDimension: z.string(),+});++export const stringDateTime = z.string().datetime({ offset: true });++export const views = z.enum([+ "traces",+ "observations",+ "scores-numeric",+ "scores-categorical",+ // "sessions",+ // "users",+]);++export const dimension = z.object({+ field: z.string(),+});++export const metricAggregations = z.enum([+ "sum",+ "avg",+ "count",+ "max",+ "min",+ "p50",+ "p75",+ "p90",+ "p95",+ "p99",+]);++export const metric = z.object({+ measure: z.string(),+ aggregation: metricAggregations,+});++export const granularities = z.enum([+ "auto",+ "minute",+ "hour",+ "day",+ "week",+ "month",+]);++export type QueryType = z.infer<typeof query>;++export const query = z+ .object({+ view: views,+ dimensions: z.array(dimension),+ metrics: z.array(metric),+ filters: z.array(singleFilter),+ timeDimension: z+ .object({+ // TODO: We may want to extend this and allow custom intervals like 3h in the future.+ // auto tries to bin the data into approximately 50 buckets given the time range+ granularity: granularities,+ })+ .nullable(),+ fromTimestamp: stringDateTime,+ toTimestamp: stringDateTime,+ orderBy: z+ .array(+ z.object({+ field: z.string(),+ direction: z.enum(["asc", "desc"]),+ }),+ )+ .nullable(),+ })+ .refine(+ (query) =>+ // Ensure fromTimestamp is before toTimestamp+ new Date(query.fromTimestamp) < new Date(query.toTimestamp),+ );diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex b78c676991..1c9395a5c7 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -138,35 +138,24 @@ export default function Dashboard() {[dateRange],);- const timeFilter = dateRange- ? [- {- type: "datetime" as const,- column: "startTime",- operator: ">" as const,- value: dateRange.from,- },- {- type: "datetime" as const,- column: "startTime",- operator: "<" as const,- value: dateRange.to,- },- ]- : [- {- type: "datetime" as const,- column: "startTime",- operator: ">" as const,- value: new Date(new Date().getTime() - 1000),- },- {- type: "datetime" as const,- column: "startTime",- operator: "<" as const,- value: new Date(),- },- ];+ const fromTimestamp = dateRange+ ? dateRange.from+ : new Date(new Date().getTime() - 1000);+ const toTimestamp = dateRange ? dateRange.to : new Date();+ const timeFilter = [+ {+ type: "datetime" as const,+ column: "startTime",+ operator: ">" as const,+ value: fromTimestamp,+ },+ {+ type: "datetime" as const,+ column: "startTime",+ operator: "<" as const,+ value: toTimestamp,+ },+ ];const environmentFilter = convertSelectedEnvironmentsToFilter(["environment"],@@ -248,7 +237,9 @@ export default function Dashboard() {<TracesBarListChartclassName="col-span-1 xl:col-span-2"projectId={projectId}- globalFilterState={mergedFilterState}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}isLoading={environmentFilterOptions.isLoading}/>{!disableExpensiveDashboardComponents && (diff --git a/web/src/pages/project/[projectId]/queryPlayground.tsx b/web/src/pages/project/[projectId]/queryPlayground.tsxnew file mode 100644index 0000000000..e111fbfdf4--- /dev/null+++ b/web/src/pages/project/[projectId]/queryPlayground.tsx@@ -0,0 +1,137 @@+import { useSession } from "next-auth/react";+import { useRouter } from "next/router";+import { useState } from "react";+import { api } from "@/src/utils/api";+import Page from "@/src/components/layouts/page";+import { Button } from "@/src/components/ui/button";+import { CodeMirrorEditor } from "@/src/components/editor/CodeMirrorEditor";+import { Card } from "@/src/components/ui/card";+import { MarkdownJsonView } from "@/src/components/ui/MarkdownJsonView";+import { env } from "@/src/env.mjs";++export default function QueryPlayground() {+ const session = useSession();+ const isCloudAdmin =+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined &&+ session.data?.user?.admin === true;++ const router = useRouter();+ const projectId = router.query.projectId as string;+ const [queryCode, setQueryCode] = useState<string>(`{+ "view": "traces",+ "dimensions": [{ "field": "name" }],+ "metrics": [{ "measure": "count", "aggregation": "count" }],+ "filters": [],+ "timeDimension": {+ "granularity": "day"+ },+ "fromTimestamp": "${new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()}",+ "toTimestamp": "${new Date().toISOString()}",+ "page": 0,+ "limit": 50+}`);+ const [error, setError] = useState<string | null>(null);++ // Query execution state+ const [queryInput, setQueryInput] = useState<any>(null);++ // Execute query mutation+ const { data, isLoading } = api.dashboard.executeQuery.useQuery(+ {+ projectId,+ query: queryInput?.query || {+ view: "traces",+ dimensions: [],+ metrics: [],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(+ Date.now() - 7 * 24 * 60 * 60 * 1000,+ ).toISOString(),+ toTimestamp: new Date().toISOString(),+ page: 0,+ limit: 10,+ },+ },+ {+ enabled: !!queryInput, // Only run the query when queryInput is set (via button click)+ retry: false,+ },+ );++ const executeQuery = () => {+ setError(null);+ try {+ // Parse the JSON query+ const parsedQuery = JSON.parse(queryCode);+ setQueryInput({+ projectId,+ query: parsedQuery,+ });+ } catch (err) {+ setError(`Invalid JSON: ${(err as Error).message}`);+ }+ };++ return (+ isCloudAdmin && (+ <Page+ headerProps={{+ title: "Query Playground",+ help: {+ description:+ "Test and visualize queries using Langfuse's query builder",+ href: "https://langfuse.com/docs", // Update with actual docs link when available+ },+ }}+ >+ <div className="flex h-full flex-col gap-4 overflow-hidden">+ <div className="grid min-h-0 flex-1 grid-cols-2 gap-4 overflow-hidden">+ {/* Query Editor */}+ <Card className="flex flex-col overflow-hidden p-4">+ <h2 className="mb-2 text-lg font-medium">Query</h2>+ <div className="flex-1 overflow-hidden">+ <CodeMirrorEditor+ value={queryCode}+ onChange={setQueryCode}+ mode="json"+ className="h-full"+ minHeight={100}+ />+ </div>+ <div className="mt-4 flex items-center justify-between">+ <div className="text-sm text-red-500">{error}</div>+ <Button+ onClick={executeQuery}+ disabled={isLoading && !!queryInput}+ >+ {isLoading && !!queryInput ? "Running..." : "Run Query"}+ </Button>+ </div>+ </Card>++ {/* Results */}+ <Card className="flex flex-col overflow-hidden p-4">+ <h2 className="mb-2 text-lg font-medium">Results</h2>+ <div className="flex-1 overflow-auto">+ {data ? (+ <div className="h-full overflow-auto">+ <MarkdownJsonView content={data} />+ </div>+ ) : (+ <div className="flex h-full items-center justify-center p-4 text-muted-foreground">+ {isLoading && !!queryInput+ ? "Loading results..."+ : error+ ? "Query error"+ : "Write a query and click 'Run Query' to see results"}+ </div>+ )}+ </div>+ </Card>+ </div>+ </div>+ </Page>+ )+ );+}