🪢 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
chore: remove obsolete dashboard queries (#6303)
Steffen Schmitz28e61fae0b7c
diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.tsindex c72a48a9f9..8b680afab8 100644--- a/packages/shared/src/server/repositories/dashboards.ts+++ b/packages/shared/src/server/repositories/dashboards.ts@@ -10,7 +10,6 @@ import { convertDateToClickhouseDateTime } from "../clickhouse/client";import {OBSERVATIONS_TO_TRACE_INTERVAL,SCORE_TO_TRACE_OBSERVATIONS_INTERVAL,- TRACE_TO_OBSERVATIONS_INTERVAL,} from "./constants";export type DateTrunc = "year" | "month" | "week" | "day" | "hour" | "minute";@@ -35,103 +34,6 @@ const convertEnvFilterToClickhouseFilter = (filter: FilterState) => {]);};-export const getTotalTraces = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- ).apply();-- const query = `- SELECT- count(id) as count- FROM traces t FINAL- WHERE project_id = {projectId: String}- AND ${chFilter.query}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- `;-- const result = await queryClickhouse<{ count: number }>({- query,- params: {- projectId,- ...chFilter.params,- ...environmentFilter.params,- },- tags: {- feature: "dashboard",- type: "totalTraces",- kind: "analytic",- projectId,- },- });-- if (result.length === 0) {- return undefined;- }-- return [{ countTraceId: result[0].count }];-};--export const getObservationsCostGroupedByName = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- const hasTraceFilter = chFilter.find((f) => f.clickhouseTable === "traces");-- const query = `- SELECT- provided_model_name as name,- sumMap(cost_details)['total'] as sum_cost_details,- sumMap(usage_details)['total'] as sum_usage_details- FROM observations o FINAL ${hasTraceFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}- WHERE project_id = {projectId: String}- ${appliedFilter.query ? `AND ${appliedFilter.query}` : ""}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- GROUP BY provided_model_name- ORDER BY sumMap(cost_details)['total'] DESC- LIMIT 50- `;-- const result = await queryClickhouse<{- name: string;- sum_cost_details: number;- sum_usage_details: number;- }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- },- tags: {- feature: "dashboard",- type: "observationCostGroupedByName",- kind: "analytic",- projectId,- },- });-- return result;-};-export const getScoreAggregate = async (projectId: string,filter: FilterState,@@ -199,138 +101,6 @@ export const getScoreAggregate = async (return result;};-export const groupTracesByTime = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- ).apply();-- const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(- filter,- "timestamp",- );-- const query = `- SELECT- ${selectTimeseriesColumn(bucketSizeInSeconds, "timestamp", "timestamp")},- count(*) as count- FROM traces t FINAL- WHERE project_id = {projectId: String}- AND ${chFilter.query}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- GROUP BY timestamp- ${orderByQuery}- `;- const result = await queryClickhouse<{- timestamp: string;- count: string;- }>({- query,- params: {- projectId,- ...chFilter.params,- ...environmentFilter.params,- ...orderByParams,- },- tags: {- feature: "dashboard",- type: "tracesByTime",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),- countTraceId: Number(row.count),- }));-};--export const getTotalObservationUsageByTimeByModel = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- const tracesFilter = chFilter.find((f) => f.clickhouseTable === "traces");- const timeFilter = tracesFilter- ? (chFilter.find(- (f) =>- f.clickhouseTable === "observations" &&- f.field.includes("start_time") &&- (f.operator === ">=" || f.operator === ">"),- ) as DateTimeFilter | undefined)- : undefined;-- const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(- filter,- "start_time",- );-- const query = `- SELECT- ${selectTimeseriesColumn(bucketSizeInSeconds, "start_time", "start_time")},- sumMap(usage_details)['total'] as units,- sumMap(cost_details)['total'] as cost,- provided_model_name- FROM observations o FINAL- ${tracesFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}- WHERE project_id = {projectId: String}- AND ${appliedFilter.query}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- ${timeFilter ? `AND t.timestamp >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}- GROUP BY start_time, provided_model_name- ${orderByQuery}- `;-- const result = await queryClickhouse<{- start_time: string;- units: string;- cost: string;- provided_model_name: string;- }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- ...orderByParams,- ...(timeFilter- ? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }- : {}),- },- tags: {- feature: "dashboard",- type: "observationUsageByTime",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- startTime: parseClickhouseUTCDateTimeFormat(row.start_time),- units: Number(row.units),- cost: Number(row.cost),- model: row.provided_model_name,- }));-};-export const getObservationCostByTypeByTime = async (projectId: string,filter: FilterState,@@ -527,604 +297,6 @@ export const getObservationUsageByTypeByTime = async (});};-export const getDistinctModels = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- const tracesFilter = chFilter.find((f) => f.clickhouseTable === "traces");- const timeFilter = tracesFilter- ? (chFilter.find(- (f) =>- f.clickhouseTable === "observations" &&- f.field.includes("start_time") &&- (f.operator === ">=" || f.operator === ">"),- ) as DateTimeFilter | undefined)- : undefined;-- // No need for final as duplicates are caught by distinct anyway.- const query = `- SELECT distinct(provided_model_name) as model, count(*) as count- FROM observations o- ${tracesFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}- WHERE project_id = {projectId: String}- AND ${appliedFilter.query}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- ${timeFilter ? `AND t.timestamp >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}- GROUP BY provided_model_name- ORDER BY count(*) DESC- LIMIT 1000- `;-- const result = await queryClickhouse<{ model: string }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- ...(timeFilter- ? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }- : {}),- },- tags: {- feature: "dashboard",- type: "distinctModels",- kind: "analytic",- projectId,- },- });-- return result;-};--export const getScoresAggregateOverTime = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");- // TODO: Validate whether we can filter traces on timestamp here.-- const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(- filter,- "timestamp",- );-- const query = `- SELECT- ${selectTimeseriesColumn(bucketSizeInSeconds, "timestamp", "timestamp")},- name,- data_type,- source,- AVG(value) as avg_value- FROM scores FINAL- ${traceFilter ? "JOIN traces t ON scores.trace_id = t.id AND scores.project_id = t.project_id" : ""}- WHERE project_id = {projectId: String}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- AND ${appliedFilter.query}- AND data_type IN ('NUMERIC', 'BOOLEAN')- GROUP BY- timestamp,- name,- data_type,- source- ${orderByQuery};-`;-- const result = await queryClickhouse<{- timestamp: string;- name: string;- data_type: string;- source: string;- avg_value: number;- }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- ...orderByParams,- },- tags: {- feature: "dashboard",- type: "scoresAggregateOverTime",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- scoreTimestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),- scoreName: row.name,- scoreDataType: row.data_type,- scoreSource: row.source,- avgValue: Number(row.avg_value),- }));-};--export const getModelUsageByUser = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- const timeFilter = chFilter.find(- (f) =>- f.clickhouseTable === "observations" &&- f.field.includes("start_time") &&- (f.operator === ">=" || f.operator === ">"),- ) as DateTimeFilter | undefined;-- const query = `- SELECT- sumMap(usage_details)['total'] as sum_usage_details,- sumMap(cost_details)['total'] as sum_cost_details,- user_id- FROM observations o FINAL- JOIN traces t FINAL- ON o.trace_id = t.id AND o.project_id = t.project_id- WHERE project_id = {projectId: String}- AND t.user_id IS NOT NULL- AND ${appliedFilter.query}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- ${timeFilter ? `AND t.timestamp >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}- GROUP BY user_id- ORDER BY sum_cost_details DESC- `;-- const result = await queryClickhouse<{- sum_usage_details: string;- sum_cost_details: number;- user_id: string;- }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- ...(timeFilter- ? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }- : {}),- },- tags: {- feature: "dashboard",- type: "modelUsageByUser",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- sumUsageDetails: Number(row.sum_usage_details),- sumCostDetails: Number(row.sum_cost_details),- userId: row.user_id,- }));-};--export const getObservationLatencies = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- // Skipping FINAL here, as the quantiles are approximate to begin with.- const query = `- SELECT- quantiles(0.5, 0.9, 0.95, 0.99)(date_diff('millisecond', o.start_time, o.end_time)) as quantiles,- name- FROM observations o- ${chFilter.find((f) => f.clickhouseTable === "traces") ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}- WHERE project_id = {projectId: String}- AND ${appliedFilter.query}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- GROUP BY name- ORDER BY quantiles[2] DESC- `;-- const result = await queryClickhouse<{ quantiles: string[]; name: string }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- },- tags: {- feature: "dashboard",- type: "observationLatencies",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- p50: Number(row.quantiles[0]) / 1000,- p90: Number(row.quantiles[1]) / 1000,- p95: Number(row.quantiles[2]) / 1000,- p99: Number(row.quantiles[3]) / 1000,- name: row.name,- }));-};--export const getTracesLatencies = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- const timestampFilter = chFilter.find(- (f) =>- f.clickhouseTable === "traces" &&- f.field === 't."timestamp"' &&- (f.operator === ">=" || f.operator === ">"),- ) as DateTimeFilter | undefined;-- // Skipping FINAL here, as the quantiles are approximate to begin with.- const query = `- WITH trace_latencies as (- select o.trace_id,- t.name,- o.project_id,- date_diff('millisecond', min(o.start_time), coalesce(max(o.end_time), max(o.start_time))) as duration- FROM traces t- JOIN observations o- ON o.trace_id = t.id AND o.project_id = t.project_id- WHERE project_id = {projectId: String}- AND ${appliedFilter.query}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- ${timestampFilter ? `AND o.start_time > {dateTimeFilterObservations: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}- GROUP BY o.project_id, o.trace_id, t.name- )-- SELECT- quantiles(0.5, 0.9, 0.95, 0.99)(duration) as quantiles,- name- FROM trace_latencies- GROUP BY name- ORDER BY quantiles[2] DESC- `;-- const result = await queryClickhouse<{ quantiles: string[]; name: string }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- ...(timestampFilter- ? { dateTimeFilterObservations: timestampFilter.value }- : {}),- },- tags: {- feature: "dashboard",- type: "tracesLatencies",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- p50: Number(row.quantiles[0]) / 1000,- p90: Number(row.quantiles[1]) / 1000,- p95: Number(row.quantiles[2]) / 1000,- p99: Number(row.quantiles[3]) / 1000,- name: row.name,- }));-};--export const getModelLatenciesOverTime = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );-- const appliedFilter = chFilter.apply();-- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");-- const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(- filter,- "start_time_bucket",- );-- // Skipping FINAL here, as the quantiles are approximate to begin with.- const query = `- SELECT- ${selectTimeseriesColumn(bucketSizeInSeconds, "o.start_time", "start_time_bucket")},- provided_model_name,- quantiles(0.5, 0.75, 0.9, 0.95, 0.99)(date_diff('millisecond', o.start_time, o.end_time)) as quantiles- FROM observations o- ${traceFilter ? "JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}- WHERE project_id = {projectId: String}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- AND ${appliedFilter.query}- GROUP BY provided_model_name, start_time_bucket- ${orderByQuery};-`;-- const result = await queryClickhouse<{- start_time_bucket: string;- provided_model_name: string;- quantiles: string[];- }>({- query,- params: {- projectId,- ...appliedFilter.params,- ...environmentFilter.params,- ...orderByParams,- },- tags: {- feature: "dashboard",- type: "modelLatenciesOverTime",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- p50: Number(row.quantiles[0]) / 1000,- p75: Number(row.quantiles[1]) / 1000,- p90: Number(row.quantiles[2]) / 1000,- p95: Number(row.quantiles[3]) / 1000,- p99: Number(row.quantiles[4]) / 1000,- model: row.provided_model_name,- start_time: parseClickhouseUTCDateTimeFormat(row.start_time_bucket),- }));-};--export const getNumericScoreTimeSeries = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );- const chFilterRes = chFilter.apply();-- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");-- const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(- filter,- "score_timestamp",- );-- const query = `- SELECT- ${selectTimeseriesColumn(bucketSizeInSeconds, "s.timestamp", "score_timestamp")},- s.name as score_name,- AVG(s.value) as avg_value- FROM scores s final- ${traceFilter ? "JOIN traces t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}- WHERE s.project_id = {projectId: String}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- ${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}- GROUP BY score_name, score_timestamp- ${orderByQuery}- `;-- const result = await queryClickhouse<{- score_timestamp: string;- score_name: string;- avg_value: number;- }>({- query,- params: {- projectId,- ...(chFilterRes ? chFilterRes.params : {}),- ...environmentFilter.params,- ...orderByParams,- },- tags: {- feature: "dashboard",- type: "numericScoreTimeSeries",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- scoreTimestamp: parseClickhouseUTCDateTimeFormat(row.score_timestamp),- scoreName: row.score_name,- avgValue: Number(row.avg_value),- }));-};--export const getCategoricalScoreTimeSeries = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );- const chFilterRes = chFilter.apply();-- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");-- const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(- filter,- "score_timestamp",- );-- const query = `- SELECT- ${bucketSizeInSeconds ? selectTimeseriesColumn(bucketSizeInSeconds, "s.timestamp", "score_timestamp") + ", " : ""}- s.name as score_name,- s.data_type as score_data_type,- s.source as score_source,- s.string_value as score_value,- count(s.string_value) as count- FROM scores s final- ${traceFilter ? "JOIN traces t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}- WHERE s.project_id = {projectId: String}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- ${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}- GROUP BY score_name, score_data_type, score_source, score_value ${bucketSizeInSeconds ? ", score_timestamp" : ""}- ${orderByQuery}- `;-- const result = await queryClickhouse<{- score_timestamp?: string;- score_name: string;- score_data_type: string;- score_source: string;- score_value: string;- count: number;- }>({- query,- params: {- projectId,- ...(chFilterRes ? chFilterRes.params : {}),- ...environmentFilter.params,- ...orderByParams,- },- tags: {- feature: "dashboard",- type: "categoricalScoreTimeSeries",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- scoreTimestamp: row.score_timestamp- ? parseClickhouseUTCDateTimeFormat(row.score_timestamp)- : undefined,- scoreName: row.score_name,- scoreDataType: row.score_data_type,- scoreSource: row.score_source,- scoreValue: row.score_value,- count: Number(row.count),- }));-};--export const getObservationsStatusTimeSeries = async (- projectId: string,- filter: FilterState,-) => {- const { envFilter, remainingFilters } =- extractEnvironmentFilterFromFilters(filter);- const environmentFilter = new FilterList(- convertEnvFilterToClickhouseFilter(envFilter),- ).apply();- const chFilter = new FilterList(- createFilterFromFilterState(remainingFilters, dashboardColumnDefinitions),- );- const chFilterRes = chFilter.apply();-- const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");-- const [orderByQuery, orderByParams, bucketSizeInSeconds] = orderByTimeSeries(- filter,- "start_time_bucket",- );-- const query = `- SELECT- ${bucketSizeInSeconds ? selectTimeseriesColumn(bucketSizeInSeconds, "o.start_time", "start_time_bucket") + ", " : ""}- count(*) as observation_count,- level as level- FROM observations o- ${traceFilter ? "JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}- WHERE project_id = {projectId: String}- ${environmentFilter.query ? `AND ${environmentFilter.query}` : ""}- AND o.level IS NOT NULL- AND ${chFilterRes?.query}- GROUP BY level ${bucketSizeInSeconds ? ", start_time_bucket" : ""}- ${orderByQuery}- `;-- const result = await queryClickhouse<{- start_time_bucket?: string;- observation_count: string;- level: string;- }>({- query,- params: {- projectId,- ...(chFilterRes ? chFilterRes.params : {}),- ...environmentFilter.params,- ...orderByParams,- },- tags: {- feature: "dashboard",- type: "observationStatusTimeSeries",- kind: "analytic",- projectId,- },- });-- return result.map((row) => ({- start_time_bucket: row.start_time_bucket- ? parseClickhouseUTCDateTimeFormat(row.start_time_bucket)- : undefined,- count: Number(row.observation_count),- level: row.level,- }));-};-export const orderByTimeSeries = (filter: FilterState,col: string,diff --git a/web/src/__tests__/queryBuilderDashboards.servertest.ts b/web/src/__tests__/queryBuilderDashboards.servertest.tsindex 4d5bff4a52..b2e6736004 100644--- a/web/src/__tests__/queryBuilderDashboards.servertest.ts+++ b/web/src/__tests__/queryBuilderDashboards.servertest.ts@@ -4,27 +4,10 @@ import {createTracesCh,createObservation,createObservationsCh,- getTotalTraces,- getTracesGroupedByName,- getObservationsCostGroupedByName,- getScoreAggregate,- groupTracesByTime,- getTotalObservationUsageByTimeByModel,- getModelUsageByUser,- getTracesGroupedByUsers,- getObservationLatencies,- getTracesLatencies,- getModelLatenciesOverTime,} 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 testsconst projectId = randomUUID();@@ -217,21 +200,8 @@ describe("selfServeDashboards", () => {});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+ it("should return the correct total trace count", async () => {+ // Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "traces",dimensions: [],@@ -243,40 +213,19 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Assert that both results match+ // Assert that the result matches the expected count from sample dataexpect(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+ // 1. Define a query with filter for production environmentconst prodQueryBuilderQuery: QueryType = {view: "traces",dimensions: [],@@ -294,37 +243,20 @@ describe("selfServeDashboards", () => {toTimestamp: defaultToTime,orderBy: null,};++ // 2. Get result for production environmentconst prodQueryBuilderResult = await executeQuery(projectId,prodQueryBuilderQuery,);- // 3. Assert that both results match and only count production traces+ // 3. Assert that the result matches the expected count for production tracesexpect(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);+ // 4. Define a query with filter for development environmentconst devQueryBuilderQuery: QueryType = {...prodQueryBuilderQuery,filters: [@@ -336,43 +268,22 @@ describe("selfServeDashboards", () => {},],};++ // 5. Get result for development environmentconst devQueryBuilderResult = await executeQuery(projectId,devQueryBuilderQuery,);- // 5. Assert development environment results+ // 6. Assert that the result matches the expected count for development tracesexpect(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+ // 1. Define a query with multiple filters for recent production tracesconst queryBuilderQuery: QueryType = {view: "traces",dimensions: [],@@ -396,32 +307,24 @@ describe("selfServeDashboards", () => {toTimestamp: defaultToTime,orderBy: null,};++ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 3. Assert that both results match and only count recent production traces+ // 3. Assert that the result matches the expected count for recent production tracesexpect(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+ it("should return traces grouped by name correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "traces",dimensions: [{ field: "name" }],@@ -433,56 +336,32 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst 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+ // 3. Verify results match the expected trace counts by nameObject.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(resultRow).toBeDefined();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);+ // 4. Verify result set has the expected number of rowsexpect(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+ // 1. Define a query with filter for production environmentconst queryBuilderQuery: QueryType = {view: "traces",dimensions: [{ field: "name" }],@@ -501,48 +380,40 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 4. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 5. Verify results+ // 3. Verify results// Get only traces with production environmentconst productionTraceNames = ["chat-completion", "embeddings"];- // Verify both results have the expected number of rows- expect(legacyResult.length).toBe(productionTraceNames.length);+ // Verify result has the expected number of rowsexpect(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+ // Check each production trace name is presentproductionTraceNames.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);+ // Verify the count matches what we expect based on our sample data+ // We can calculate this from our stats object or hardcode based on our test data+ if (traceName === "chat-completion") {+ expect(Number(resultRow?.count_count)).toBe(7); // 5 recent + 2 older traces+ } else if (traceName === "embeddings") {+ expect(Number(resultRow?.count_count)).toBe(3);+ }});});});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+ it("should return observations grouped by model with cost and token metrics", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "observations",dimensions: [{ field: "providedModelName" }],@@ -557,53 +428,42 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Verify both results+ // 3. Verify resultsexpect(queryBuilderResult).toBeDefined();- expect(legacyResult).toBeDefined();- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [item.name, item]),- );+ // Expected models based on our test data+ const expectedModels = [+ "gpt-4-turbo",+ "text-embedding-ada-002",+ "claude-3-opus",+ ];- // Verify each model's costs and token usage match- queryBuilderResult.forEach((row: any) => {- const modelName = row.provided_model_name;- const legacyModelData = legacyResultMap.get(modelName);+ // Verify we have the expected number of models+ expect(queryBuilderResult.length).toBe(expectedModels.length);- expect(legacyModelData).toBeDefined();- expect(row.sum_total_cost).toBe(legacyModelData?.sum_cost_details);- expect(row.sum_total_tokens).toBe(legacyModelData?.sum_usage_details);- });+ // Verify each model is present with cost and token metrics+ expectedModels.forEach((modelName) => {+ const modelRow = queryBuilderResult.find(+ (row: any) => row.provided_model_name === modelName,+ );++ expect(modelRow).toBeDefined();+ expect(modelRow.sum_total_cost).toBeDefined();+ expect(modelRow.sum_total_tokens).toBeDefined();- // Verify both result sets have the same number of models- expect(legacyResult.length).toBe(queryBuilderResult.length);+ // We could add more specific assertions about the expected costs and tokens+ // if we had that information calculated from our sample data+ });});it("should filter observations by traceName", async () => {- // 1. Define a filter for chat-completion trace- const traceNameFilter: FilterState = [- {- type: "string",- operator: "=",- column: "traceName",- value: "chat-completion",- },- ];-- // 2. Get legacy result with filter- const legacyResult = await getObservationsCostGroupedByName(- projectId,- traceNameFilter,- );-- // 3. Define the equivalent query for the query builder+ // 1. Define a query with filter for chat-completion traceconst queryBuilderQuery: QueryType = {view: "observations",dimensions: [{ field: "providedModelName" }],@@ -625,50 +485,23 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 4. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 5. Verify results- // Verify both results have the same number of rows- expect(queryBuilderResult.length).toBe(legacyResult.length);-- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [item.name, item]),- );-- // Verify each model is present with correct costs- queryBuilderResult.forEach((row: any) => {- const modelName = row.provided_model_name;- const legacyModelData = legacyResultMap.get(modelName);+ // 3. Verify results+ expect(queryBuilderResult.length).toBe(2);- expect(legacyModelData).toBeDefined();- expect(row.sum_total_cost).toBe(legacyModelData?.sum_cost_details);- expect(row.sum_total_tokens).toBe(legacyModelData?.sum_usage_details);- });+ const modelRow = queryBuilderResult[0];+ expect(modelRow.provided_model_name).toBe("gpt-4-turbo");+ expect(modelRow.sum_total_cost).toBe(900);+ expect(modelRow.sum_total_tokens).toBe("20736");});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+ // 1. Define a query with filter for production environmentconst queryBuilderQuery: QueryType = {view: "observations",dimensions: [{ field: "providedModelName" }],@@ -690,250 +523,36 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 4. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 5. Verify results+ // 3. Verify results// Production models should only include gpt-4-turbo and text-embedding-ada-002+ // based on our sample dataconst productionModels = ["gpt-4-turbo", "text-embedding-ada-002"];- // Verify both results have the expected number of rows- expect(legacyResult.length).toBe(productionModels.length);+ // Verify result has the expected number of rowsexpect(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,- );+ // Verify each production model is present+ productionModels.forEach((modelName) => {+ const modelRow = queryBuilderResult.find(+ (row: any) => row.provided_model_name === modelName,+ );- 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),- );- }+ expect(modelRow).toBeDefined();+ expect(modelRow.sum_total_cost).toBeGreaterThan(500);+ expect(Number(modelRow.sum_total_tokens)).toBeGreaterThan(10000);});-- // 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+ it("should return traces grouped by time correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "traces",dimensions: [],@@ -947,53 +566,45 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst 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);+ // 3. Verify results+ // Result should have multiple rows (one per hour in the time range)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);- }+ // Each row should have a time_dimension and count_count+ queryBuilderResult.forEach((row: any) => {+ expect(row.time_dimension).toBeDefined();+ expect(Number(row.count_count)).toBeGreaterThanOrEqual(0);});++ // Verify that the hours where we created traces have non-zero counts+ // Our test data has traces at specific times+ const recentHours = queryBuilderResult.filter(+ (row: any) =>+ new Date(row.time_dimension).getTime() >= oneHourAgo.getTime() &&+ new Date(row.time_dimension).getTime() <= now.getTime(),+ );++ // We should have at least one hour with traces in the recent period+ expect(recentHours.length).toBeGreaterThan(0);++ // At least one of the recent hours should have a non-zero count+ const hasNonZeroCount = recentHours.some(+ (row: any) => Number(row.count_count) > 0,+ );+ expect(hasNonZeroCount).toBe(true);});});describe("observations-total-cost-by-model-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 getTotalObservationUsageByTimeByModel(- 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+ it("should return observations cost by model over time correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "observations",dimensions: [{ field: "providedModelName" }],@@ -1010,61 +621,58 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Verify both results+ // 3. Verify resultsexpect(queryBuilderResult).toBeDefined();- expect(legacyResult).toBeDefined();- // Verify both result sets have 70 to 80 rows- expect(legacyResult.length).toBeGreaterThanOrEqual(70);- expect(legacyResult.length).toBeLessThanOrEqual(80);+ // Result should have multiple rows (one per hour per model in the time range)expect(queryBuilderResult.length).toBeGreaterThanOrEqual(70);expect(queryBuilderResult.length).toBeLessThanOrEqual(80);- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [- `${item.model}-${item.startTime.getTime()}`,- item,- ]),+ // Each row should have these properties+ queryBuilderResult.forEach((row: any) => {+ expect(row.time_dimension).toBeDefined();+ expect(row.provided_model_name).toBeDefined();+ expect(row.sum_total_cost).toBeDefined();+ expect(row.sum_total_tokens).toBeDefined();+ });++ // Verify that the hours where we created observations have non-zero costs/tokens+ // Our test data has observations at specific times+ const expectedModels = [+ "gpt-4-turbo",+ "text-embedding-ada-002",+ "claude-3-opus",+ ];++ // Filter for recent hours where we created observations+ const recentObservations = queryBuilderResult.filter(+ (row: any) =>+ new Date(row.time_dimension).getTime() >= oneHourAgo.getTime() &&+ new Date(row.time_dimension).getTime() <= now.getTime() &&+ expectedModels.includes(row.provided_model_name),);- // Verify each model's costs and token usage match- queryBuilderResult.forEach((row: any) => {- const key = `${row.provided_model_name}-${new Date(row.time_dimension).getTime()}`;- const legacyData = legacyResultMap.get(key);+ // We should have at least one recent observation+ expect(recentObservations.length).toBeGreaterThan(0);- expect(legacyData).toBeDefined();- expect(Number(row.sum_total_cost)).toBe(Number(legacyData?.cost));- expect(Number(row.sum_total_tokens)).toBe(Number(legacyData?.units));- });+ // At least one of the recent observations should have non-zero cost/tokens+ const hasNonZeroValues = recentObservations.some(+ (row: any) =>+ Number(row.sum_total_cost) > 0 && Number(row.sum_total_tokens) > 0,+ );+ expect(hasNonZeroValues).toBe(true);});});describe("observations-usage-by-users 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 getModelUsageByUser(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+ it("should return observations usage by users correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "observations",dimensions: [{ field: "userId" }],@@ -1076,63 +684,43 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Verify both results+ // 3. Verify resultsexpect(queryBuilderResult).toBeDefined();- expect(legacyResult).toBeDefined();-- // Verify both result sets have the same number of rows- expect(legacyResult.length).toBe(queryBuilderResult.length);- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [item.userId, item]),- );-- // Verify each user's costs and token usage match- queryBuilderResult.forEach((row: any) => {- const userId = row.user_id;- const legacyData = legacyResultMap.get(userId);+ // Based on our sample data, we should have observations for users A, B, D, and E+ // (these are the users associated with traces that have observations)+ const expectedUsers = ["user-A", "user-B", "user-D", "user-E"];- expect(legacyData).toBeDefined();- expect(Number(row.sum_total_cost)).toBe(- Number(legacyData?.sumCostDetails),+ // Check that we have results for the expected users+ expectedUsers.forEach((userId) => {+ const userRow = queryBuilderResult.find(+ (row: any) => row.user_id === userId,);++ // We might not have observations for all users, so we'll just check+ // that the structure is correct for the ones we do have+ if (userRow) {+ expect(userRow.sum_total_cost).toBeDefined();+ }});++ // At least one user should have a non-zero cost+ const hasNonZeroCost = queryBuilderResult.some(+ (row: any) => Number(row.sum_total_cost) > 0,+ );+ expect(hasNonZeroCost).toBe(true);});});describe("traces-grouped-by-user 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 getTracesGroupedByUsers(- projectId,- [- {- type: "datetime",- operator: ">=",- column: "timestamp",- value: new Date(defaultFromTime),- },- {- type: "datetime",- operator: "<=",- column: "timestamp",- value: new Date(defaultToTime),- },- ],- undefined,- 1000,- 0,- dashboardColumnDefinitions,- );-- // 2. Define the equivalent query for the query builder+ it("should return traces grouped by user correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "traces",dimensions: [{ field: "userId" }],@@ -1144,54 +732,51 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Verify both results+ // 3. Verify resultsexpect(queryBuilderResult).toBeDefined();- expect(legacyResult).toBeDefined();- // Verify both result sets have the same number of rows- expect(legacyResult.length).toBe(queryBuilderResult.length);+ // Based on our sample data, we should have traces for users A through F+ const expectedUsers = [+ "user-A",+ "user-B",+ "user-C",+ "user-D",+ "user-E",+ "user-F",+ ];- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [item.user, item]),- );+ // Check that we have results for all expected users+ expectedUsers.forEach((userId) => {+ const userRow = queryBuilderResult.find(+ (row: any) => row.user_id === userId,+ );- // Verify each user's trace count matches- queryBuilderResult.forEach((row: any) => {- const userId = row.user_id;- const legacyData = legacyResultMap.get(userId);+ expect(userRow).toBeDefined();+ expect(userRow.count_count).toBeDefined();- expect(legacyData).toBeDefined();- expect(Number(row.count_count)).toBe(Number(legacyData?.count));+ // Verify the count matches what we expect based on our sample data+ // We could add more specific assertions if needed+ expect(Number(userRow.count_count)).toBeGreaterThan(0);});++ // Verify the total number of traces across all users matches our expected total+ const totalTraces = queryBuilderResult.reduce(+ (sum, row) => sum + Number(row.count_count),+ 0,+ );+ expect(totalTraces).toBe(stats.totalTraces);});});describe("observation-latencies-aggregated 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 getObservationLatencies(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+ it("should return observation latencies aggregated correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "observations",dimensions: [{ field: "name" }],@@ -1208,65 +793,60 @@ describe("selfServeDashboards", () => {orderBy: [{ field: "p95_latency", direction: "desc" }],};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Verify both results+ // 3. Verify resultsexpect(queryBuilderResult).toBeDefined();- expect(legacyResult).toBeDefined();-- // Verify both result sets have the same number of rows- expect(legacyResult.length).toBe(queryBuilderResult.length);-- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [item.name, item]),- );- // Verify each observation's latency metrics match- queryBuilderResult.forEach((row: any) => {- const name = row.name;- const legacyData = legacyResultMap.get(name);+ // Based on our sample data, we should have observations for these models+ const expectedModels = [+ "gpt-4-turbo",+ "text-embedding-ada-002",+ "claude-3-opus",+ ];- expect(legacyData).toBeDefined();- expect(Number(row.p50_latency) / 1000).toBeCloseTo(- Number(legacyData?.p50),- );- expect(Number(row.p90_latency) / 1000).toBeCloseTo(- Number(legacyData?.p90),- );- expect(Number(row.p95_latency) / 1000).toBeCloseTo(- Number(legacyData?.p95),- );- expect(Number(row.p99_latency) / 1000).toBeCloseTo(- Number(legacyData?.p99),+ // Check that we have results for the expected models+ expectedModels.forEach((modelName) => {+ const modelRow = queryBuilderResult.find(+ (row: any) => row.name === modelName,);++ // We might not have latency data for all models, so we'll just check+ // that the structure is correct for the ones we do have+ if (modelRow) {+ expect(modelRow.p50_latency).toBeDefined();+ expect(modelRow.p90_latency).toBeDefined();+ expect(modelRow.p95_latency).toBeDefined();+ expect(modelRow.p99_latency).toBeDefined();++ // Latencies should be positive numbers+ expect(Number(modelRow.p50_latency)).toBeGreaterThan(0);+ expect(Number(modelRow.p90_latency)).toBeGreaterThan(0);+ expect(Number(modelRow.p95_latency)).toBeGreaterThan(0);+ expect(Number(modelRow.p99_latency)).toBeGreaterThan(0);++ // Percentiles should be in ascending order+ expect(Number(modelRow.p50_latency)).toBeLessThanOrEqual(+ Number(modelRow.p90_latency),+ );+ expect(Number(modelRow.p90_latency)).toBeLessThanOrEqual(+ Number(modelRow.p95_latency),+ );+ expect(Number(modelRow.p95_latency)).toBeLessThanOrEqual(+ Number(modelRow.p99_latency),+ );+ }});});});describe("traces-latencies-aggregated 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 getTracesLatencies(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+ it("should return trace latencies aggregated correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "traces",dimensions: [{ field: "name" }],@@ -1283,65 +863,58 @@ describe("selfServeDashboards", () => {orderBy: [{ field: "p95_latency", direction: "desc" }],};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Verify both results+ // 3. Verify resultsexpect(queryBuilderResult).toBeDefined();- expect(legacyResult).toBeDefined();-- // Verify both result sets have the same number of rows- expect(legacyResult.length).toBe(queryBuilderResult.length);-- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [item.name, item]),- );- // Verify each trace's latency metrics match- queryBuilderResult.forEach((row: any) => {- const name = row.name;- const legacyData = legacyResultMap.get(name);+ // Based on our sample data, we should have traces with these names+ const expectedTraceNames = [+ "chat-completion",+ "embeddings",+ "summarize",+ "qa-bot",+ ];- expect(legacyData).toBeDefined();- expect(Number(row.p50_latency) / 1000).toBeCloseTo(- Number(legacyData?.p50),- );- expect(Number(row.p90_latency) / 1000).toBeCloseTo(- Number(legacyData?.p90),- );- expect(Number(row.p95_latency) / 1000).toBeCloseTo(- Number(legacyData?.p95),- );- expect(Number(row.p99_latency) / 1000).toBeCloseTo(- Number(legacyData?.p99),+ // Check that we have results for the expected trace names+ expectedTraceNames.forEach((traceName) => {+ const traceRow = queryBuilderResult.find(+ (row: any) => row.name === traceName,);++ // We might not have latency data for all trace types, so we'll just check+ // that the structure is correct for the ones we do have+ if (traceRow) {+ expect(traceRow.p50_latency).toBeDefined();+ expect(traceRow.p90_latency).toBeDefined();+ expect(traceRow.p95_latency).toBeDefined();+ expect(traceRow.p99_latency).toBeDefined();++ // If we have latency data, it should be valid+ if (Number(traceRow.p50_latency) > 0) {+ // Percentiles should be in ascending order+ expect(Number(traceRow.p50_latency)).toBeLessThanOrEqual(+ Number(traceRow.p90_latency),+ );+ expect(Number(traceRow.p90_latency)).toBeLessThanOrEqual(+ Number(traceRow.p95_latency),+ );+ expect(Number(traceRow.p95_latency)).toBeLessThanOrEqual(+ Number(traceRow.p99_latency),+ );+ }+ }});});});describe("model-latencies-over-time 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 getModelLatenciesOverTime(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+ it("should return model latencies over time correctly", async () => {+ // 1. Define the query for the query builderconst queryBuilderQuery: QueryType = {view: "observations",dimensions: [{ field: "providedModelName" }],@@ -1361,58 +934,74 @@ describe("selfServeDashboards", () => {orderBy: null,};- // 3. Get result using the query builder+ // 2. Get result using the query builderconst queryBuilderResult = await executeQuery(projectId,queryBuilderQuery,);- // 4. Verify both results+ // 3. Verify resultsexpect(queryBuilderResult).toBeDefined();- expect(legacyResult).toBeDefined();- // Verify both result sets have a similar number of rows- // The exact number might differ due to time granularity differences+ // Result should have multiple rows (one per hour per model in the time range)expect(queryBuilderResult.length).toBeGreaterThan(0);- expect(legacyResult.length).toBeGreaterThan(0);-- // Create maps for easier comparison- const legacyResultMap = new Map(- legacyResult.map((item) => [- `${item.model}-${new Date(item.start_time).getTime()}`,- item,- ]),- );- // Verify model latency metrics match for some samples- // Note: We can't check all rows as the time granularity might differ- let matchCount = 0;+ // Each row should have these propertiesqueryBuilderResult.forEach((row: any) => {- const key = `${row.provided_model_name}-${new Date(row.time_dimension).getTime()}`;- const legacyData = legacyResultMap.get(key);-- if (legacyData && !isNaN(legacyData?.p50)) {- matchCount++;- expect(Number(row.p50_latency) / 1000).toBeCloseTo(- Number(legacyData.p50),- );- expect(Number(row.p75_latency) / 1000).toBeCloseTo(- Number(legacyData.p75),- );- expect(Number(row.p90_latency) / 1000).toBeCloseTo(- Number(legacyData.p90),- );- expect(Number(row.p95_latency) / 1000).toBeCloseTo(- Number(legacyData.p95),- );- expect(Number(row.p99_latency) / 1000).toBeCloseTo(- Number(legacyData.p99),- );- }+ expect(row.time_dimension).toBeDefined();+ expect(row.provided_model_name).toBeDefined();+ expect(row.p50_latency).toBeDefined();+ expect(row.p75_latency).toBeDefined();+ expect(row.p90_latency).toBeDefined();+ expect(row.p95_latency).toBeDefined();+ expect(row.p99_latency).toBeDefined();});- // Ensure we found at least some matches- expect(matchCount).toBeGreaterThan(0);+ // Verify that the hours where we created observations have valid latency data+ // Our test data has observations at specific times+ const expectedModels = [+ "gpt-4-turbo",+ "text-embedding-ada-002",+ "claude-3-opus",+ ];++ // Filter for recent hours where we created observations+ const recentObservations = queryBuilderResult.filter(+ (row: any) =>+ new Date(row.time_dimension).getTime() >= oneHourAgo.getTime() &&+ new Date(row.time_dimension).getTime() <= now.getTime() &&+ expectedModels.includes(row.provided_model_name),+ );++ // We should have at least one recent observation with latency data+ const hasLatencyData = recentObservations.some(+ (row: any) =>+ Number(row.p50_latency) > 0 &&+ Number(row.p75_latency) > 0 &&+ Number(row.p90_latency) > 0 &&+ Number(row.p95_latency) > 0 &&+ Number(row.p99_latency) > 0,+ );++ if (hasLatencyData) {+ // For rows with latency data, verify percentiles are in ascending order+ recentObservations.forEach((row) => {+ if (Number(row.p50_latency) > 0) {+ expect(Number(row.p50_latency)).toBeLessThanOrEqual(+ Number(row.p75_latency),+ );+ expect(Number(row.p75_latency)).toBeLessThanOrEqual(+ Number(row.p90_latency),+ );+ expect(Number(row.p90_latency)).toBeLessThanOrEqual(+ Number(row.p95_latency),+ );+ expect(Number(row.p95_latency)).toBeLessThanOrEqual(+ Number(row.p99_latency),+ );+ }+ });+ }});});});diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.tsindex 430b97149f..3c208c5296 100644--- a/web/src/features/dashboard/server/dashboard-router.ts+++ b/web/src/features/dashboard/server/dashboard-router.ts@@ -33,25 +33,11 @@ export const dashboardRouter = createTRPCRouter({filter: filterInterface.optional(),queryName: z.enum([- // "traces-total",- // "traces-grouped-by-name",- // "observations-model-cost",+ // Current score table is weird and does not fit into new model. Keep around as is until we decide what to do with it."score-aggregate",- // "traces-timeseries",- // "observations-total-cost-by-model-timeseries",- // Cost by type and usage by type are currently not supported in the new data model+ // Cost by type and usage by type are currently not supported in the new data model."observations-usage-by-type-timeseries","observations-cost-by-type-timeseries",- // "distinct-models",- // "scores-aggregate-timeseries",- // "observations-usage-by-users",- // "traces-grouped-by-user",- // "observation-latencies-aggregated",- // "traces-latencies-aggregated",- // "model-latencies-over-time",- // "numeric-score-time-series",- // "categorical-score-chart",- // "observations-status-timeseries",]).nullish(),}),@@ -67,37 +53,6 @@ export const dashboardRouter = createTRPCRouter({}switch (input.queryName) {- // case "traces-total":- // const count = await getTotalTraces(- // input.projectId,- // input.filter ?? [],- // );- // return count as DatabaseRow[];- // case "traces-grouped-by-name":- // return (- // await getTracesGroupedByName(- // input.projectId,- // dashboardColumnDefinitions,- // input.filter,- // )- // ).map(- // (row) =>- // ({- // traceName: row.name,- // countTraceId: row.count,- // }) as DatabaseRow,- // );- // case "observations-model-cost":- // const cost = await getObservationsCostGroupedByName(- // input.projectId,- // input.filter ?? [],- // );- //- // return cost.map((row) => ({- // model: row.name,- // sumCalculatedTotalCost: row.sum_cost_details,- // sumTotalTokens: row.sum_usage_details,- // })) as DatabaseRow[];case "score-aggregate":const scores = await getScoreAggregate(input.projectId,@@ -110,141 +65,18 @@ export const dashboardRouter = createTRPCRouter({avgValue: row.avg_value,countScoreId: Number(row.count),})) as DatabaseRow[];- // case "traces-timeseries":- // const rows = await groupTracesByTime(- // input.projectId,- // input.filter ?? [],- // );- //- // return rows as DatabaseRow[];- // case "observations-total-cost-by-model-timeseries":- // const dateTruncObs = extractTimeSeries(input.groupBy);- // if (!dateTruncObs) {- // return [];- // }- // const rowsObs = await getTotalObservationUsageByTimeByModel(- // input.projectId,- // input.filter ?? [],- // );- //- // return rowsObs as DatabaseRow[];case "observations-usage-by-type-timeseries":const rowsObsType = await getObservationUsageByTypeByTime(input.projectId,input.filter ?? [],);-return rowsObsType as DatabaseRow[];case "observations-cost-by-type-timeseries":const rowsObsCostByType = await getObservationCostByTypeByTime(input.projectId,input.filter ?? [],);-return rowsObsCostByType as DatabaseRow[];- // case "distinct-models":- // const models = await getDistinctModels(- // input.projectId,- // input.filter ?? [],- // );- // return models as DatabaseRow[];- // case "scores-aggregate-timeseries":- // const aggregatedScores = await getScoresAggregateOverTime(- // input.projectId,- // input.filter ?? [],- // );- //- // return aggregatedScores as DatabaseRow[];- // case "observations-usage-by-users":- // const rowsUsers = await getModelUsageByUser(- // input.projectId,- // input.filter ?? [],- // );- //- // return rowsUsers.map((row) => ({- // sumTotalTokens: row.sumUsageDetails,- // sumCalculatedTotalCost: row.sumCostDetails,- // user: row.userId,- // })) as DatabaseRow[];- // case "traces-grouped-by-user":- // const traces = await getTracesGroupedByUsers(- // input.projectId,- // input.filter ?? [],- // undefined,- // 1000,- // 0,- // dashboardColumnDefinitions,- // );- //- // return traces.map((row) => ({- // user: row.user,- // countTraceId: Number(row.count),- // })) as DatabaseRow[];- // case "observation-latencies-aggregated":- // const latencies = await getObservationLatencies(- // input.projectId,- // input.filter ?? [],- // );- //- // return latencies.map((row) => ({- // name: row.name,- // percentile50Duration: row.p50,- // percentile90Duration: row.p90,- // percentile95Duration: row.p95,- // percentile99Duration: row.p99,- // })) as DatabaseRow[];- // case "model-latencies-over-time":- // const modelLatencies = await getModelLatenciesOverTime(- // input.projectId,- // input.filter ?? [],- // );- //- // return modelLatencies.map((row) => ({- // model: row.model,- // startTime: row.start_time,- // percentile50Duration: row.p50,- // percentile75Duration: row.p75,- // percentile90Duration: row.p90,- // percentile95Duration: row.p95,- // percentile99Duration: row.p99,- // })) as DatabaseRow[];- // case "traces-latencies-aggregated":- // const traceLatencies = await getTracesLatencies(- // input.projectId,- // input.filter ?? [],- // );- //- // return traceLatencies.map((row) => ({- // traceName: row.name,- // percentile50Duration: row.p50,- // percentile90Duration: row.p90,- // percentile95Duration: row.p95,- // percentile99Duration: row.p99,- // })) as DatabaseRow[];- // case "numeric-score-time-series":- // const dateTruncNumericScoreTimeSeries = extractTimeSeries(- // input.groupBy,- // );- // if (!dateTruncNumericScoreTimeSeries) {- // return [];- // }- // const numericScoreTimeSeries = await getNumericScoreTimeSeries(- // input.projectId,- // input.filter ?? [],- // );- // return numericScoreTimeSeries as DatabaseRow[];- // case "categorical-score-chart":- // const categoricalScoreTimeSeries =- // await getCategoricalScoreTimeSeries(- // input.projectId,- // input.filter ?? [],- // );- // return categoricalScoreTimeSeries as DatabaseRow[];- // case "observations-status-timeseries":- // return (await getObservationsStatusTimeSeries(- // input.projectId,- // input.filter ?? [],- // )) as DatabaseRow[];default:throw new TRPCError({code: "NOT_FOUND",@@ -279,15 +111,6 @@ export const dashboardRouter = createTRPCRouter({}),});-// const extractTimeSeries = (groupBy?: z.infer<typeof groupByInterface>) => {-// const temporal = groupBy?.find((group) => {-// if (group.type === "datetime") {-// return group;-// }-// });-// return temporal?.type === "datetime" ? temporal.temporalUnit : undefined;-// };-/*** Execute a query using the QueryBuilder.*