Skip to content

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

fix: traces table performance (#881)

Max Deichmann9a3adf54b1df
diff --git a/src/__tests__/server/api/routers/traces.servertest.ts b/src/__tests__/server/api/routers/traces.servertest.ts
index 6ec28d1691..de1bb261ab 100644
--- a/src/__tests__/server/api/routers/traces.servertest.ts
+++ b/src/__tests__/server/api/routers/traces.servertest.ts
@@ -53,7 +53,7 @@ describe("Traces TRPC Router", () => {
orderBy: null,
});
expect(traces).toBeDefined();
- expect(traces).toMatchObject([trace]);
+ expect(traces).toMatchObject({ traces: [trace] });
});
test("traces.all RPC orders traces by userId", async () => {
@@ -88,7 +88,7 @@ describe("Traces TRPC Router", () => {
order: "ASC",
},
});
- expect(tracesASC).toMatchObject([trace1, trace2]);
+ expect(tracesASC).toMatchObject({ traces: [trace1, trace2] });
const tracesDESC = await caller.traces.all({
page: 0,
@@ -102,6 +102,6 @@ describe("Traces TRPC Router", () => {
order: "DESC",
},
});
- expect(tracesDESC).toMatchObject([trace2, trace1]);
+ expect(tracesDESC).toMatchObject({ traces: [trace2, trace1] });
});
});
diff --git a/src/components/star-toggle.tsx b/src/components/star-toggle.tsx
index 2a0d419bbb..9a55b2fcc2 100644
--- a/src/components/star-toggle.tsx
+++ b/src/components/star-toggle.tsx
@@ -83,15 +83,20 @@ export function StarTraceToggle({
utils.traces.all.setData(
tracesFilter,
(oldQueryData: RouterOutput["traces"]["all"] | undefined) => {
- return oldQueryData
- ? oldQueryData.map((trace) => {
- return {
- ...trace,
- bookmarked:
- trace.id === traceId ? !trace.bookmarked : trace.bookmarked,
- };
- })
- : [];
+ return {
+ totalCount: oldQueryData?.totalCount,
+ traces: oldQueryData?.traces
+ ? oldQueryData.traces.map((trace) => {
+ return {
+ ...trace,
+ bookmarked:
+ trace.id === traceId
+ ? !trace.bookmarked
+ : trace.bookmarked,
+ };
+ })
+ : [],
+ };
},
);
void utils.traces.all.invalidate();
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index 636567990f..bee6d7ea77 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -109,12 +109,12 @@ export default function TracesTable({
};
const traces = api.traces.all.useQuery(tracesAllQueryFilter);
- const totalCount = traces.data?.slice(1)[0]?.totalCount ?? 0;
+ const totalCount = traces.data?.totalCount ?? 0;
useEffect(() => {
if (traces.isSuccess) {
setDetailPageList(
"traces",
- traces.data.map((t) => t.id),
+ traces.data.traces.map((t) => t.id),
);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -137,7 +137,7 @@ export default function TracesTable({
);
const convertToTableRow = (
- trace: RouterOutput["traces"]["all"][0],
+ trace: RouterOutput["traces"]["all"]["traces"][0],
): TracesTableRow => {
return {
bookmarked: trace.bookmarked,
@@ -403,7 +403,8 @@ export default function TracesTable({
<TraceTableMultiSelectAction
// Exclude traces that are not in the current page
selectedTraceIds={Object.keys(selectedRows).filter(
- (traceId) => traces.data?.map((t) => t.id).includes(traceId),
+ (traceId) =>
+ traces.data?.traces.map((t) => t.id).includes(traceId),
)}
projectId={projectId}
onDeleteSuccess={() => {
@@ -428,11 +429,11 @@ export default function TracesTable({
: {
isLoading: false,
isError: false,
- data: traces.data.map((t) => convertToTableRow(t)),
+ data: traces.data.traces.map((t) => convertToTableRow(t)),
}
}
pagination={{
- pageCount: Math.ceil(totalCount / paginationState.pageSize),
+ pageCount: Math.ceil(Number(totalCount) / paginationState.pageSize),
onChange: setPaginationState,
state: paginationState,
}}
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 2c1288f212..e8b1b87059 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -22,6 +22,8 @@ import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
import { TRPCError } from "@trpc/server";
import { orderBy } from "@/src/server/api/interfaces/orderBy";
import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";
+import { type Sql } from "@prisma/client/runtime/library";
+import { instrumentAsync } from "@/src/utils/instrumentation";
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -70,58 +72,8 @@ export const traceRouter = createTRPCRouter({
)`
: Prisma.empty;
- const query = Prisma.sql`
- WITH usage AS (
- SELECT
- trace_id,
- sum(prompt_tokens) AS "promptTokens",
- sum(completion_tokens) AS "completionTokens",
- sum(total_tokens) AS "totalTokens"
- FROM
- "observations"
- WHERE
- "trace_id" IS NOT NULL
- AND "type" = 'GENERATION'
- AND "project_id" = ${input.projectId}
- ${observationTimeseriesFilter}
- GROUP BY
- trace_id
- ),
- trace_latency AS (
- SELECT
- trace_id,
- EXTRACT(EPOCH FROM COALESCE(MAX("end_time"), MAX("start_time"))) - EXTRACT(EPOCH FROM MIN("start_time"))::double precision AS "latency"
- FROM
- "observations"
- WHERE
- "trace_id" IS NOT NULL
- AND "project_id" = ${input.projectId}
- ${observationTimeseriesFilter}
- GROUP BY
- trace_id
- ),
- -- used for filtering
- scores_avg AS (
- SELECT
- trace_id,
- jsonb_object_agg(name::text, avg_value::double precision) AS scores_avg
- FROM (
- SELECT
- trace_id,
- name,
- avg(value) avg_value
- FROM
- scores
- GROUP BY
- 1,
- 2
- ORDER BY
- 1) tmp
- GROUP BY
- 1
- )
- SELECT
- t.*,
+ const tracesQuery = createTracesQuery(
+ Prisma.sql`t.*,
t."user_id" AS "userId",
t."metadata" AS "metadata",
t.session_id AS "sessionId",
@@ -130,33 +82,47 @@ export const traceRouter = createTRPCRouter({
COALESCE(u."completionTokens", 0)::int AS "completionTokens",
COALESCE(u."totalTokens", 0)::int AS "totalTokens",
tl.latency AS "latency",
- (count(*) OVER ())::int AS "totalCount"
- FROM
- "traces" AS t
- LEFT JOIN usage AS u ON u.trace_id = t.id
- -- used for filtering
- LEFT JOIN scores_avg AS s_avg ON s_avg.trace_id = t.id
- LEFT JOIN trace_latency AS tl ON tl.trace_id = t.id
- WHERE
- t."project_id" = ${input.projectId}
- ${searchCondition}
- ${filterCondition}
- ${orderByCondition}
- LIMIT ${input.limit}
- OFFSET ${input.page * input.limit}
- `;
+ (count(*) OVER ())::int AS "totalCount"`,
+ input.projectId,
+ observationTimeseriesFilter,
+ input.page,
+ input.limit,
+ searchCondition,
+ filterCondition,
+ orderByCondition,
+ );
+
+ const traces = await instrumentAsync({ name: "get-all-traces" }, () =>
+ ctx.prisma.$queryRaw<
+ Array<
+ Trace & {
+ promptTokens: number;
+ completionTokens: number;
+ totalTokens: number;
+ totalCount: number;
+ latency: number | null;
+ }
+ >
+ >(tracesQuery),
+ );
- const traces = await ctx.prisma.$queryRaw<
- Array<
- Trace & {
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
- totalCount: number;
- latency: number | null;
- }
- >
- >(query);
+ const countQyery = createTracesQuery(
+ Prisma.sql`count(*)`,
+ input.projectId,
+ observationTimeseriesFilter,
+ input.page,
+ input.limit,
+ searchCondition,
+ filterCondition,
+ Prisma.empty,
+ );
+
+ const totalTraces = await instrumentAsync(
+ { name: "get-total-traces" },
+ () => ctx.prisma.$queryRaw<Array<{ count: bigint }>>(countQyery),
+ );
+
+ console.log(totalTraces);
// get scores for each trace individually to increase
// performance of the query above
@@ -170,10 +136,13 @@ export const traceRouter = createTRPCRouter({
},
},
});
- return traces.map((trace) => {
- const filteredScores = scores.filter((s) => s.traceId === trace.id);
- return { ...trace, scores: filteredScores };
- });
+ return {
+ traces: traces.map((trace) => {
+ const filteredScores = scores.filter((s) => s.traceId === trace.id);
+ return { ...trace, scores: filteredScores };
+ }),
+ totalCount: totalTraces[0]?.count,
+ };
}),
filterOptions: protectedProjectProcedure
.input(z.object({ projectId: z.string() }))
@@ -405,3 +374,81 @@ export const traceRouter = createTRPCRouter({
}
}),
});
+
+function createTracesQuery(
+ select: Sql,
+ projectId: string,
+ observationTimeseriesFilter: Sql,
+ page: number,
+ limit: number,
+ searchCondition: Sql,
+ filterCondition: Sql,
+ orderByCondition: Sql,
+) {
+ return Prisma.sql`
+ WITH usage AS (
+ SELECT
+ trace_id,
+ sum(prompt_tokens) AS "promptTokens",
+ sum(completion_tokens) AS "completionTokens",
+ sum(total_tokens) AS "totalTokens"
+ FROM
+ "observations"
+ WHERE
+ "trace_id" IS NOT NULL
+ AND "type" = 'GENERATION'
+ AND "project_id" = ${projectId}
+ ${observationTimeseriesFilter}
+ GROUP BY
+ trace_id
+ ),
+ trace_latency AS (
+ SELECT
+ trace_id,
+ EXTRACT(EPOCH FROM COALESCE(MAX("end_time"), MAX("start_time"))) - EXTRACT(EPOCH FROM MIN("start_time"))::double precision AS "latency"
+ FROM
+ "observations"
+ WHERE
+ "trace_id" IS NOT NULL
+ AND "project_id" = ${projectId}
+ ${observationTimeseriesFilter}
+ GROUP BY
+ trace_id
+ ),
+ -- used for filtering
+ scores_avg AS (
+ SELECT
+ trace_id,
+ jsonb_object_agg(name::text, avg_value::double precision) AS scores_avg
+ FROM (
+ SELECT
+ trace_id,
+ name,
+ avg(value) avg_value
+ FROM
+ scores
+ GROUP BY
+ 1,
+ 2
+ ORDER BY
+ 1) tmp
+ GROUP BY
+ 1
+ )
+ SELECT
+ ${select}
+ FROM
+ "traces" AS t
+ LEFT JOIN usage AS u ON u.trace_id = t.id
+ -- used for filtering
+ LEFT JOIN scores_avg AS s_avg ON s_avg.trace_id = t.id
+ LEFT JOIN trace_latency AS tl ON tl.trace_id = t.id
+ WHERE
+ t."project_id" = ${projectId}
+ ${searchCondition}
+ ${filterCondition}
+ ${orderByCondition}
+ LIMIT ${limit}
+ OFFSET ${page * limit}
+`;
+}