Skip to content

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

chore: move the traces timeseries chart to new query builder (#6226)

Steffen Schmitz64f6051048f6
diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.ts
index bd7c452448..bd8a66ec8e 100644
--- a/packages/shared/src/server/clickhouse/client.ts
+++ b/packages/shared/src/server/clickhouse/client.ts
@@ -26,6 +26,7 @@ export const clickhouseClient = (
database: env.CLICKHOUSE_DB,
http_headers: headers,
clickhouse_settings: {
+ ...(params.opts?.clickhouse_settings ?? {}),
log_comment: JSON.stringify(params.tags ?? {}),
async_insert: 1,
wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.ts
index 33d80e5b7c..173472e2e9 100644
--- a/web/src/__tests__/queryBuilder.servertest.ts
+++ b/web/src/__tests__/queryBuilder.servertest.ts
@@ -1451,6 +1451,83 @@ describe("queryBuilder", () => {
});
expect(embeddingsDayBefore?.count_count).toBe("1"); // 1 embeddings trace day before yesterday
});
+
+ it("should ensure time_dimension adheres to ISO8601 date format", async () => {
+ // Setup
+ const projectId = randomUUID();
+ const now = new Date();
+
+ // Create traces with specific timestamps
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ name: "test-trace-1",
+ environment: "production",
+ timestamp: now.getTime(),
+ }),
+ createTrace({
+ project_id: projectId,
+ name: "test-trace-2",
+ environment: "production",
+ timestamp: now.getTime() - 86400000, // 1 day ago
+ }),
+ ];
+ await createTracesCh(traces);
+
+ // Define query with time dimension
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: {
+ granularity: "hour",
+ },
+ fromTimestamp: new Date(now.getTime() - 172800000).toISOString(), // 2 days ago
+ toTimestamp: now.toISOString(),
+ orderBy: null,
+ };
+
+ // Execute query
+ const queryBuilder = new QueryBuilder();
+ const { query: compiledQuery, parameters } = queryBuilder.build(
+ query,
+ projectId,
+ );
+
+ const result = await (
+ await clickhouseClient({
+ opts: {
+ clickhouse_settings: {
+ date_time_output_format: "iso",
+ },
+ },
+ }).query({
+ query: compiledQuery,
+ query_params: parameters,
+ })
+ ).json();
+
+ // Verify we have results
+ expect(result.data.length).toBeGreaterThan(0);
+
+ // Check that time_dimension values adhere to ISO8601 format
+ for (const row of result.data) {
+ expect(row).toHaveProperty("time_dimension");
+
+ // ISO8601 regex pattern
+ // This pattern matches ISO8601 dates in format: YYYY-MM-DD or YYYY-MM-DDThh:mm:ss.sssZ
+ const iso8601Pattern =
+ /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/;
+
+ expect(row.time_dimension).toMatch(iso8601Pattern);
+
+ // Verify that JavaScript Date constructor can parse the time_dimension
+ const date = new Date(row.time_dimension);
+ expect(date).toBeInstanceOf(Date);
+ expect(date.toString()).not.toBe("Invalid Date");
+ }
+ });
});
describe("scores-numeric view", () => {
diff --git a/web/src/features/dashboard/components/ModelCostTable.tsx b/web/src/features/dashboard/components/ModelCostTable.tsx
index 18bc860421..ada221a497 100644
--- a/web/src/features/dashboard/components/ModelCostTable.tsx
+++ b/web/src/features/dashboard/components/ModelCostTable.tsx
@@ -29,7 +29,6 @@ export const ModelCostTable = ({
toTimestamp: Date;
isLoading?: boolean;
}) => {
- // Define the query using the new QueryType structure
const modelCostQuery: QueryType = {
view: "observations",
dimensions: [{ field: "providedModelName" }],
@@ -52,7 +51,6 @@ export const ModelCostTable = ({
orderBy: null,
};
- // Execute the query using the new dashboard.executeQuery functionality
const metrics = api.dashboard.executeQuery.useQuery(
{
projectId,
diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index 261904bc7d..8578ef014b 100644
--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -5,42 +5,48 @@ import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTim
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
import { compactNumberFormatter } from "@/src/utils/numbers";
import { isEmptyTimeSeries } from "@/src/features/dashboard/components/hooks";
-import {
- dashboardDateRangeAggregationSettings,
- type DashboardDateRangeAggregationOption,
-} from "@/src/utils/date-range-utils";
+import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
+import {
+ type QueryType,
+ mapLegacyUiTableFilterToView,
+} from "@/src/features/query";
export const TracesAndObservationsTimeSeriesChart = ({
className,
projectId,
globalFilterState,
+ fromTimestamp,
+ toTimestamp,
agg,
isLoading = false,
}: {
className?: string;
projectId: string;
globalFilterState: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
agg: DashboardDateRangeAggregationOption;
isLoading?: boolean;
}) => {
- const traces = api.dashboard.chart.useQuery(
+ const tracesQuery: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: mapLegacyUiTableFilterToView("traces", globalFilterState),
+ timeDimension: {
+ granularity: "auto",
+ },
+ fromTimestamp: fromTimestamp.toISOString(),
+ toTimestamp: toTimestamp.toISOString(),
+ orderBy: null,
+ };
+
+ const traces = api.dashboard.executeQuery.useQuery(
{
projectId,
- from: "traces",
- select: [{ column: "traceId", agg: "COUNT" }],
- filter: globalFilterState.map((f) =>
- f.type === "datetime" ? { ...f, column: "timestamp" } : f,
- ),
- groupBy: [
- {
- type: "datetime",
- column: "timestamp",
- temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,
- },
- ],
- queryName: "traces-timeseries",
+ query: tracesQuery,
},
{
trpc: {
@@ -55,14 +61,11 @@ export const TracesAndObservationsTimeSeriesChart = ({
const transformedTraces = traces.data
? traces.data.map((item) => {
return {
- ts: (item.timestamp as Date).getTime(),
+ ts: new Date(item.time_dimension as any).getTime(),
values: [
{
label: "Traces",
- value:
- typeof item.countTraceId === "number"
- ? item.countTraceId
- : undefined,
+ value: Number(item.count_count),
},
],
};
@@ -70,25 +73,26 @@ export const TracesAndObservationsTimeSeriesChart = ({
: [];
const total = traces.data?.reduce((acc, item) => {
- return acc + (item.countTraceId as number);
+ return acc + Number(item.count_count);
}, 0);
- const observations = api.dashboard.chart.useQuery(
+ const observationsQuery: QueryType = {
+ view: "observations",
+ dimensions: [{ field: "level" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: mapLegacyUiTableFilterToView("observations", globalFilterState),
+ timeDimension: {
+ granularity: "auto",
+ },
+ fromTimestamp: fromTimestamp.toISOString(),
+ toTimestamp: toTimestamp.toISOString(),
+ orderBy: null,
+ };
+
+ const observations = api.dashboard.executeQuery.useQuery(
{
projectId,
- from: "traces",
- select: [{ column: "traceId", agg: "COUNT" }],
- filter: globalFilterState.map((f) =>
- f.type === "datetime" ? { ...f, column: "timestamp" } : f,
- ),
- groupBy: [
- {
- type: "datetime",
- column: "timestamp",
- temporalUnit: dashboardDateRangeAggregationSettings[agg].date_trunc,
- },
- ],
- queryName: "observations-status-timeseries",
+ query: observationsQuery,
},
{
trpc: {
@@ -111,7 +115,7 @@ export const TracesAndObservationsTimeSeriesChart = ({
}
>
>((acc, item) => {
- const ts = (item.start_time_bucket as Date).getTime();
+ const ts = new Date(item.time_dimension as any).getTime();
if (!acc[ts]) {
acc[ts] = {
ts,
@@ -120,7 +124,7 @@ export const TracesAndObservationsTimeSeriesChart = ({
}
acc[ts].values.push({
label: item.level as string,
- value: typeof item.count === "number" ? item.count : undefined,
+ value: Number(item.count_count),
});
return acc;
@@ -129,7 +133,7 @@ export const TracesAndObservationsTimeSeriesChart = ({
: [];
const totalObservations = observations.data?.reduce((acc, item) => {
- return acc + (item.count as number);
+ return acc + Number(item.count_count);
}, 0);
const data = [
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index de11df5497..3d970761d8 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -330,6 +330,11 @@ export async function executeQuery(
const result = await queryClickhouse<Record<string, unknown>>({
query: compiledQuery,
params: parameters,
+ clickhouseConfigs: {
+ clickhouse_settings: {
+ date_time_output_format: "iso",
+ },
+ },
tags: {
feature: "custom-queries",
type: query.view,
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index c6f88d41ad..7f298f6cbe 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -254,7 +254,9 @@ export default function Dashboard() {
<TracesAndObservationsTimeSeriesChart
className="col-span-1 xl:col-span-3"
projectId={projectId}
- globalFilterState={mergedFilterState}
+ globalFilterState={[...userFilterState, ...environmentFilter]}
+ fromTimestamp={fromTimestamp}
+ toTimestamp={toTimestamp}
agg={agg}
isLoading={environmentFilterOptions.isLoading}
/>