Skip to content

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

percentiles for latency dashboard (#359)

Max Deichmann9f7c016133bb
diff --git a/src/__tests__/query-builder.servertest.ts b/src/__tests__/query-builder.servertest.ts
index 1ef2660e27..4dcc72ffe5 100644
--- a/src/__tests__/query-builder.servertest.ts
+++ b/src/__tests__/query-builder.servertest.ts
@@ -4,7 +4,9 @@ import {
enrichAndCreateQuery,
executeQuery,
} from "@/src/server/api/services/query-builder";
+import { type aggregations } from "@/src/server/api/services/sqlInterface";
import { prisma } from "@/src/server/db";
+import { type z } from "zod";
describe("Build valid SQL queries", () => {
beforeEach(async () => await pruneDatabase());
@@ -447,5 +449,155 @@ describe("Build valid SQL queries", () => {
]);
});
});
+
+ [
+ {
+ percentile: "50thPercentile",
+ expectedOutcome: [
+ {
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ percentile50Duration: 8,
+ },
+ {
+ startTime: new Date("2021-01-02T00:00:00.000Z"),
+ percentile50Duration: 5,
+ },
+ {
+ startTime: new Date("2021-01-03T00:00:00.000Z"),
+ percentile50Duration: null,
+ },
+ {
+ startTime: new Date("2021-01-04T00:00:00.000Z"),
+ percentile50Duration: null,
+ },
+ ],
+ },
+ {
+ percentile: "99thPercentile",
+ expectedOutcome: [
+ {
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ percentile99Duration: 10,
+ },
+ {
+ startTime: new Date("2021-01-02T00:00:00.000Z"),
+ percentile99Duration: 5,
+ },
+ {
+ startTime: new Date("2021-01-03T00:00:00.000Z"),
+ percentile99Duration: null,
+ },
+ {
+ startTime: new Date("2021-01-04T00:00:00.000Z"),
+ percentile99Duration: null,
+ },
+ ],
+ },
+ {
+ percentile: "90thPercentile",
+ expectedOutcome: [
+ {
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ percentile90Duration: 10,
+ },
+ {
+ startTime: new Date("2021-01-02T00:00:00.000Z"),
+ percentile90Duration: 5,
+ },
+ {
+ startTime: new Date("2021-01-03T00:00:00.000Z"),
+ percentile90Duration: null,
+ },
+ {
+ startTime: new Date("2021-01-04T00:00:00.000Z"),
+ percentile90Duration: null,
+ },
+ ],
+ },
+ ].forEach((props) => {
+ it(`should calculate right percentiles ${props.percentile}`, async () => {
+ await prisma.trace.create({
+ data: {
+ id: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ await prisma.observation.createMany({
+ data: [
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 5,
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ endTime: new Date("2021-01-01T00:00:10.000Z"),
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 3,
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ endTime: new Date("2021-01-01T00:00:08.000Z"),
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-1",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 3,
+ startTime: new Date("2021-01-01T00:00:00.000Z"),
+ endTime: new Date("2021-01-01T00:00:01.000Z"),
+ },
+ {
+ traceId: "trace-1",
+ name: "trace-2",
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ completionTokens: 4,
+ startTime: new Date("2021-01-02T00:00:00.000Z"),
+ endTime: new Date("2021-01-02T00:00:05.000Z"),
+ },
+ ],
+ });
+
+ const result = await executeQuery(
+ prisma,
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ {
+ from: "observations",
+ filter: [
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: ">=",
+ value: new Date("2021-01-01T00:00:00.000Z"),
+ },
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: "<=",
+ value: new Date("2021-01-04T00:00:00.000Z"),
+ },
+ ],
+ groupBy: [
+ { type: "datetime", column: "startTime", temporalUnit: "day" },
+ ],
+ select: [
+ {
+ column: "duration",
+ agg: props.percentile as z.infer<typeof aggregations>,
+ },
+ ],
+ },
+ );
+
+ expect(result).toStrictEqual(props.expectedOutcome);
+ });
+ });
});
});
diff --git a/src/features/dashboard/components/BaseTimeSeriesChart.tsx b/src/features/dashboard/components/BaseTimeSeriesChart.tsx
index 263ee09557..564c1b977a 100644
--- a/src/features/dashboard/components/BaseTimeSeriesChart.tsx
+++ b/src/features/dashboard/components/BaseTimeSeriesChart.tsx
@@ -1,5 +1,5 @@
import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";
-import { numberFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter } from "@/src/utils/numbers";
import { cn } from "@/src/utils/tailwind";
import { AreaChart } from "@tremor/react";
@@ -63,7 +63,7 @@ export function BaseTimeSeriesChart(props: {
connectNulls={props.connectNulls}
colors={["indigo", "cyan"]}
valueFormatter={
- props.valueFormatter ? props.valueFormatter : numberFormatter
+ props.valueFormatter ? props.valueFormatter : compactNumberFormatter
}
noDataText="No data"
showLegend={props.showLegend}
diff --git a/src/features/dashboard/components/LatencyChart.tsx b/src/features/dashboard/components/LatencyChart.tsx
index 13327b6f17..c6e621529c 100644
--- a/src/features/dashboard/components/LatencyChart.tsx
+++ b/src/features/dashboard/components/LatencyChart.tsx
@@ -11,6 +11,8 @@ import {
} from "@/src/features/dashboard/components/hooks";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
+import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
+import { numberFormatter } from "@/src/utils/numbers";
export const LatencyChart = ({
className,
@@ -23,10 +25,16 @@ export const LatencyChart = ({
globalFilterState: FilterState;
agg: DateTimeAggregationOption;
}) => {
- const data = api.dashboard.chart.useQuery({
+ const latencies = api.dashboard.chart.useQuery({
projectId,
from: "observations",
- select: [{ column: "duration", agg: "AVG" }, { column: "model" }],
+ select: [
+ { column: "duration", agg: "50thPercentile" },
+ { column: "duration", agg: "90thPercentile" },
+ { column: "duration", agg: "95thPercentile" },
+ { column: "duration", agg: "99thPercentile" },
+ { column: "model" },
+ ],
filter:
[
...globalFilterState,
@@ -44,27 +52,57 @@ export const LatencyChart = ({
const allModels = getAllModels(projectId, globalFilterState);
- const transformedData =
- data.data && allModels
+ const getData = (valueColumn: string) => {
+ return latencies.data && allModels
? fillMissingValuesAndTransform(
- extractTimeSeriesData(data.data, "startTime", [
- { labelColumn: "model", valueColumn: "avgDuration" },
+ extractTimeSeriesData(latencies.data, "startTime", [
+ { labelColumn: "model", valueColumn: valueColumn },
]),
allModels,
)
: [];
+ };
+
+ const data = [
+ {
+ tabTitle: "50th Percentile",
+ data: getData("percentile50Duration"),
+ },
+ {
+ tabTitle: "90th Percentile",
+ data: getData("percentile90Duration"),
+ },
+ {
+ tabTitle: "95th Percentile",
+ data: getData("percentile95Duration"),
+ },
+ {
+ tabTitle: "99th Percentile",
+ data: getData("percentile99Duration"),
+ },
+ ];
return (
<DashboardCard
className={className}
title="Model latencies"
- description="Average latency (ms) per LLM generation"
- isLoading={data.isLoading}
+ description="Latencies (seconds) per LLM generation"
+ isLoading={latencies.isLoading}
>
- <BaseTimeSeriesChart
- agg={agg}
- data={transformedData ?? []}
- connectNulls={true}
+ <TabComponent
+ tabs={data.map((item) => {
+ return {
+ tabTitle: item.tabTitle,
+ content: (
+ <BaseTimeSeriesChart
+ agg={agg}
+ data={item.data}
+ connectNulls={true}
+ valueFormatter={numberFormatter}
+ />
+ ),
+ };
+ })}
/>
</DashboardCard>
);
diff --git a/src/features/dashboard/components/MetricTable.tsx b/src/features/dashboard/components/MetricTable.tsx
index 4d8b8ba990..f73edc54fa 100644
--- a/src/features/dashboard/components/MetricTable.tsx
+++ b/src/features/dashboard/components/MetricTable.tsx
@@ -1,7 +1,7 @@
import { api } from "@/src/utils/api";
import { type FilterState } from "@/src/features/filters/types";
import { TotalMetric } from "./TotalMetric";
-import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";
import { RightAlignedCell } from "@/src/features/dashboard/components/RightAlignedCell";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
@@ -46,7 +46,7 @@ export const MetricTable = ({
item.model as string,
<RightAlignedCell key={i}>
{item.sumTotalTokens
- ? numberFormatter(item.sumTotalTokens as number)
+ ? compactNumberFormatter(item.sumTotalTokens as number)
: "0"}
</RightAlignedCell>,
<RightAlignedCell key={i}>
diff --git a/src/features/dashboard/components/ModelUsageChart.tsx b/src/features/dashboard/components/ModelUsageChart.tsx
index 4bb7b5a12e..3ee93b8888 100644
--- a/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/src/features/dashboard/components/ModelUsageChart.tsx
@@ -12,7 +12,7 @@ import {
fillMissingValuesAndTransform,
} from "@/src/features/dashboard/components/hooks";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
-import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
@@ -94,7 +94,7 @@ export const ModelUsageChart = ({
{
tabTitle: "Total tokens",
data: transformedTotalTokens,
- totalMetric: totalTokens ? numberFormatter(totalTokens) : "-",
+ totalMetric: totalTokens ? compactNumberFormatter(totalTokens) : "-",
metricDescription: `Token count`,
},
];
@@ -109,8 +109,6 @@ export const ModelUsageChart = ({
tabs={data.map((item) => {
return {
tabTitle: item.tabTitle,
- totalMetric: item.totalMetric,
- metricDescription: item.metricDescription,
content: (
<>
<TotalMetric
diff --git a/src/features/dashboard/components/ScoresTable.tsx b/src/features/dashboard/components/ScoresTable.tsx
index 14c405daa2..c98c8e1f00 100644
--- a/src/features/dashboard/components/ScoresTable.tsx
+++ b/src/features/dashboard/components/ScoresTable.tsx
@@ -1,7 +1,7 @@
import { api } from "@/src/utils/api";
import { type FilterState } from "@/src/features/filters/types";
import { TotalMetric } from "./TotalMetric";
-import { numberFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter } from "@/src/utils/numbers";
import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { NoData } from "@/src/features/dashboard/components/NoData";
@@ -119,23 +119,23 @@ export const ScoresTable = ({
data.map((item, i) => [
item.scoreName,
<RightAlignedCell key={i}>
- {numberFormatter(item.countScoreId as number)}
+ {compactNumberFormatter(item.countScoreId as number)}
</RightAlignedCell>,
<RightAlignedCell key={i}>
- {numberFormatter(item.avgValue)}
+ {compactNumberFormatter(item.avgValue)}
</RightAlignedCell>,
<RightAlignedCell key={i}>
- {numberFormatter(item.zeroValueScore as number)}
+ {compactNumberFormatter(item.zeroValueScore as number)}
</RightAlignedCell>,
<RightAlignedCell key={i}>
- {numberFormatter(item.oneValueScore)}
+ {compactNumberFormatter(item.oneValueScore)}
</RightAlignedCell>,
]) ?? []
}
collapse={{ collapsed: 5, expanded: 20 }}
>
<TotalMetric
- metric={totalScores ? numberFormatter(totalScores) : "0"}
+ metric={totalScores ? compactNumberFormatter(totalScores) : "0"}
description="Total scores tracked"
/>
</DashboardTable>
diff --git a/src/features/dashboard/components/TabsComponent.tsx b/src/features/dashboard/components/TabsComponent.tsx
index 0e835ab70d..2f9b3a5122 100644
--- a/src/features/dashboard/components/TabsComponent.tsx
+++ b/src/features/dashboard/components/TabsComponent.tsx
@@ -5,8 +5,6 @@ export type TabComponentProps = {
tabs: {
tabTitle: string;
content: ReactNode;
- totalMetric: string;
- metricDescription: string;
}[];
};
diff --git a/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index a68aecc24d..ed18f6139a 100644
--- a/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -7,7 +7,7 @@ import { type FilterState } from "@/src/features/filters/types";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { BaseTimeSeriesChart } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
-import { numberFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter } from "@/src/utils/numbers";
export const TracesTimeSeriesChart = ({
className,
@@ -67,7 +67,7 @@ export const TracesTimeSeriesChart = ({
>
<TotalMetric
description={`Traces tracked`}
- metric={total ? numberFormatter(total) : "-"}
+ metric={total ? compactNumberFormatter(total) : "-"}
/>
<BaseTimeSeriesChart
className="min-h-80 lg:h-full"
diff --git a/src/features/dashboard/components/UserChart.tsx b/src/features/dashboard/components/UserChart.tsx
index c0cc0e741e..ee485a2c0d 100644
--- a/src/features/dashboard/components/UserChart.tsx
+++ b/src/features/dashboard/components/UserChart.tsx
@@ -2,7 +2,7 @@ import { api } from "@/src/utils/api";
import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseries-aggregation";
import { type FilterState } from "@/src/features/filters/types";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
-import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
import { BarList } from "@tremor/react";
import { isNotUndefinedOrNull } from "@/src/utils/types";
@@ -108,7 +108,7 @@ export const UserChart = ({
data: isExpanded
? transformedNumberOfTraces.slice(0, maxNumberOfEntries.expanded)
: transformedNumberOfTraces.slice(0, maxNumberOfEntries.collapsed),
- totalMetric: totalTraces ? numberFormatter(totalTraces) : "-",
+ totalMetric: totalTraces ? compactNumberFormatter(totalTraces) : "-",
metricDescription: "Total traces",
},
];
@@ -123,8 +123,6 @@ export const UserChart = ({
tabs={data.map((item) => {
return {
tabTitle: item.tabTitle,
- totalMetric: item.totalMetric,
- metricDescription: item.metricDescription,
content: (
<>
<TotalMetric
diff --git a/src/features/dashboard/components/cards/BarChartCard.tsx b/src/features/dashboard/components/cards/BarChartCard.tsx
index 766af5eb81..f9d468aa10 100644
--- a/src/features/dashboard/components/cards/BarChartCard.tsx
+++ b/src/features/dashboard/components/cards/BarChartCard.tsx
@@ -1,7 +1,7 @@
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { NoData } from "@/src/features/dashboard/components/NoData";
import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";
-import { numberFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter } from "@/src/utils/numbers";
import { BarList } from "@tremor/react";
export type BarChartDataPoint = {
@@ -32,7 +32,7 @@ export default function BarChartCard({
isLoading,
children,
}: BarChartCardProps) {
- const stat = header.stat ? numberFormatter(header.stat) : "0";
+ const stat = header.stat ? compactNumberFormatter(header.stat) : "0";
return (
<DashboardCard
className={className}
diff --git a/src/pages/project/[projectId]/users.tsx b/src/pages/project/[projectId]/users.tsx
index 059a5b8f71..74da2e946d 100644
--- a/src/pages/project/[projectId]/users.tsx
+++ b/src/pages/project/[projectId]/users.tsx
@@ -7,7 +7,7 @@ import { useEffect, useState } from "react";
import TableLink from "@/src/components/table/table-link";
import { DataTable } from "@/src/components/table/data-table";
import { useRouter } from "next/router";
-import { numberFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter } from "@/src/utils/numbers";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import { type Score } from "@prisma/client";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
@@ -138,11 +138,11 @@ export default function UsersPage() {
t.firstTrace?.toLocaleString() ?? "No event yet",
lastEvent:
t.lastObservation.toLocaleString() ?? "No event yet",
- totalEvents: numberFormatter(
+ totalEvents: compactNumberFormatter(
(Number(t.totalTraces) || 0) +
(Number(t.totalObservations) || 0),
),
- totalTokens: numberFormatter(t.totalTokens),
+ totalTokens: compactNumberFormatter(t.totalTokens),
lastScore: t.lastScore,
};
}),
diff --git a/src/pages/project/[projectId]/users/[userId].tsx b/src/pages/project/[projectId]/users/[userId].tsx
index 884d6c7b37..7b676b36be 100644
--- a/src/pages/project/[projectId]/users/[userId].tsx
+++ b/src/pages/project/[projectId]/users/[userId].tsx
@@ -3,7 +3,7 @@ import Header from "@/src/components/layouts/header";
import { api } from "@/src/utils/api";
import TracesTable from "@/src/components/table/use-cases/traces";
import ScoresTable from "@/src/components/table/use-cases/scores";
-import { numberFormatter } from "@/src/utils/numbers";
+import { compactNumberFormatter } from "@/src/utils/numbers";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
import TableLink from "@/src/components/table/table-link";
import { StringParam, useQueryParam, withDefault } from "use-query-params";
@@ -122,15 +122,15 @@ function DetailsTab({ userId, projectId }: TabProps) {
{ label: "Total Traces", value: user.data.totalTraces },
{
label: "Prompt Tokens",
- value: numberFormatter(user.data.totalPromptTokens),
+ value: compactNumberFormatter(user.data.totalPromptTokens),
},
{
label: "Completion Tokens",
- value: numberFormatter(user.data.totalCompletionTokens),
+ value: compactNumberFormatter(user.data.totalCompletionTokens),
},
{
label: "Total Tokens",
- value: numberFormatter(user.data.totalTokens),
+ value: compactNumberFormatter(user.data.totalTokens),
},
]
: [];
diff --git a/src/server/api/services/query-builder.ts b/src/server/api/services/query-builder.ts
index c05e53d8fa..34c688bcae 100644
--- a/src/server/api/services/query-builder.ts
+++ b/src/server/api/services/query-builder.ts
@@ -64,27 +64,24 @@ export const createQuery = (queryUnsafe: z.TypeOf<typeof sqlInterface>) => {
const fromString = cte?.from ?? Prisma.sql` FROM ${getTableSql(query.from)}`;
- const selectFields = query.select.map((field) =>
- // raw mandatory everywhere here as this creates the selection
- // agg is typed via zod
- // column names come from our defs via the table definitions
- {
- const safeColumn = getColumnDefinition(query.from, field.column);
- return field.agg
- ? Prisma.sql`${Prisma.raw(field.agg)}(${getInternalSql(
- safeColumn,
- )}) as "${Prisma.raw(field.agg.toLowerCase())}${Prisma.raw(
- capitalizeFirstLetter(safeColumn.name),
- )}"`
- : Prisma.sql`${getInternalSql(safeColumn)} as "${Prisma.raw(
- safeColumn.name,
- )}"`;
- },
- );
+ // raw mandatory everywhere here as this creates the selection
+ // agg is typed via zod
+ // column names come from our defs via the table definitions
+ const selectedColumns = query.select.map((selectedColumn) => {
+ const safeColumn = getColumnDefinition(query.from, selectedColumn.column);
+ const safeAgg = aggregations.parse(selectedColumn.agg);
+ const columnDefinition = createAggregatedColumn(safeColumn, safeAgg);
+ return safeAgg
+ ? Prisma.sql`${columnDefinition} as "${createOutputColumnName(
+ safeColumn,
+ safeAgg,
+ )}"`
+ : Prisma.sql`${columnDefinition} as "${Prisma.raw(safeColumn.name)}"`;
+ });
if (cte)
// raw mandatory here
- selectFields.unshift(
+ selectedColumns.unshift(
Prisma.sql`date_series."date" as "${Prisma.raw(cte.column.name)}"`,
);
@@ -100,8 +97,8 @@ export const createQuery = (queryUnsafe: z.TypeOf<typeof sqlInterface>) => {
: Prisma.empty;
}
const selectString =
- selectFields.length > 0
- ? Prisma.sql` SELECT ${Prisma.join(selectFields, ", ")}`
+ selectedColumns.length > 0
+ ? Prisma.sql` SELECT ${Prisma.join(selectedColumns, ", ")}`
: Prisma.empty;
const orderByString = prepareOrderByString(
@@ -130,19 +127,76 @@ export const createQuery = (queryUnsafe: z.TypeOf<typeof sqlInterface>) => {
}${selectString}${fromString}${filterString}${groupString}${orderByString}${limitString};`;
};
+const createOutputColumnName = (
+ columnDefinition: ColumnDefinition,
+ safeAgg: z.infer<typeof aggregations>,
+): Prisma.Sql => {
+ if (!safeAgg) return Prisma.empty;
+ if (["SUM", "AVG", "COUNT", "MAX", "MIN"].includes(safeAgg)) {
+ return Prisma.sql`${Prisma.raw(safeAgg.toLowerCase())}${Prisma.raw(
+ capitalizeFirstLetter(columnDefinition.name),
+ )}`;
+ }
+
+ if (safeAgg === "50thPercentile") {
+ return Prisma.sql`percentile50${Prisma.raw(
+ capitalizeFirstLetter(columnDefinition.name),
+ )}`;
+ }
+ if (safeAgg === "90thPercentile") {
+ return Prisma.sql`percentile90${Prisma.raw(
+ capitalizeFirstLetter(columnDefinition.name),
+ )}`;
+ }
+ if (safeAgg === "95thPercentile") {
+ return Prisma.sql`percentile95${Prisma.raw(
+ capitalizeFirstLetter(columnDefinition.name),
+ )}`;
+ }
+ if (safeAgg === "99thPercentile") {
+ return Prisma.sql`percentile99${Prisma.raw(
+ capitalizeFirstLetter(columnDefinition.name),
+ )}`;
+ }
+ return Prisma.empty;
+};
+
const createAggregatedColumn = (
- from: z.infer<typeof sqlInterface>["from"],
- column: string,
+ columnDefinition: ColumnDefinition,
agg?: z.infer<typeof aggregations>,
): Prisma.Sql => {
// raw mandatory everywhere here as this creates the selection
// agg is typed via zod
// column names come from our defs via the table definitions
- return agg
- ? Prisma.sql`${Prisma.raw(
+
+ switch (agg) {
+ case "AVG":
+ case "COUNT":
+ case "MAX":
+ case "MIN":
+ case "SUM":
+ return Prisma.sql`${Prisma.raw(
aggregations.parse(agg) as string,
- )}(${getInternalSql(getColumnDefinition(from, column))})`
- : Prisma.sql`${getInternalSql(getColumnDefinition(from, column))}`;
+ )}(${getInternalSql(columnDefinition)})`;
+ case "50thPercentile":
+ return Prisma.sql`percentile_disc(0.5) within group (order by ${getInternalSql(
+ columnDefinition,
+ )})`;
+ case "90thPercentile":
+ return Prisma.sql`percentile_disc(0.9) within group (order by ${getInternalSql(
+ columnDefinition,
+ )})`;
+ case "95thPercentile":
+ return Prisma.sql`percentile_disc(0.95) within group (order by ${getInternalSql(
+ columnDefinition,
+ )})`;
+ case "99thPercentile":
+ return Prisma.sql`percentile_disc(0.99) within group (order by ${getInternalSql(
+ columnDefinition,
+ )})`;
+ case undefined:
+ return Prisma.sql`${getInternalSql(columnDefinition)}`;
+ }
};
const prepareOrderByString = (
@@ -152,10 +206,11 @@ const prepareOrderByString = (
): Prisma.Sql => {
const orderBys = (orderBy ?? []).map((orderBy) => {
// raw mandatory here
+ const safeColumn = getColumnDefinition(from, orderBy.column);
+ const safeAgg = aggregations.parse(orderBy.agg);
return Prisma.sql`${createAggregatedColumn(
- from,
- orderBy.column,
- orderBy.agg,
+ safeColumn,
+ safeAgg,
)} ${Prisma.raw(orderBy.direction)}`;
});
const addedCte = hasCte
diff --git a/src/server/api/services/sqlInterface.ts b/src/server/api/services/sqlInterface.ts
index abfb3bd216..bb29df2815 100644
--- a/src/server/api/services/sqlInterface.ts
+++ b/src/server/api/services/sqlInterface.ts
@@ -11,7 +11,17 @@ export const temporalUnit = z.enum([
]);
export const aggregations = z
- .enum(["SUM", "AVG", "COUNT", "MAX", "MIN"])
+ .enum([
+ "SUM",
+ "AVG",
+ "COUNT",
+ "MAX",
+ "MIN",
+ "50thPercentile",
+ "90thPercentile",
+ "95thPercentile",
+ "99thPercentile",
+ ])
.optional();
export const groupByInterface = z.array(
diff --git a/src/server/api/services/tableDefinitions.ts b/src/server/api/services/tableDefinitions.ts
index f6e24bd0a2..cd32b75e2f 100644
--- a/src/server/api/services/tableDefinitions.ts
+++ b/src/server/api/services/tableDefinitions.ts
@@ -44,7 +44,7 @@ export const duration = {
name: "duration",
type: "number",
internal:
- 'EXTRACT(EPOCH FROM o."end_time") * 1000 - EXTRACT(EPOCH FROM o."start_time") * 1000',
+ 'EXTRACT(EPOCH FROM o."end_time") - EXTRACT(EPOCH FROM o."start_time")',
} as const;
export const release = {
name: "release",
diff --git a/src/utils/numbers.ts b/src/utils/numbers.ts
index 4979f2aa5a..5a82d24ec1 100644
--- a/src/utils/numbers.ts
+++ b/src/utils/numbers.ts
@@ -1,7 +1,16 @@
-export const numberFormatter = (number: number) => {
+export const compactNumberFormatter = (number: number) => {
return Intl.NumberFormat("us", {
notation: "compact",
compactDisplay: "short",
+ maximumFractionDigits: 2,
+ }).format(number);
+};
+
+export const numberFormatter = (number: number) => {
+ return Intl.NumberFormat("us", {
+ notation: "standard",
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
}).format(number);
};