Skip to content

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

perf: use raw query for trace duration on dataset run table (#2286)

Hassieb Pakzad8aeec63c078c
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index d2e2f5ab63..3b06488ad7 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -586,18 +586,37 @@ export const datasetRouter = createTRPCRouter({
},
});
- const traces = await ctx.prisma.traceView.findMany({
- where: {
- id: {
- in: runItems.map((ri) => ri.traceId).filter(Boolean) as string[],
- },
- projectId: ctx.session.projectId,
- },
- select: {
- id: true,
- duration: true,
- },
- });
+ // Directly access 'traces' table and calculate duration via lateral join
+ // Previously used 'traces_view' was not performant enough
+ const traceIdsSQL = Prisma.sql`ARRAY[${Prisma.join(runItems.map((ri) => ri.traceId))}]`;
+ const traces = await ctx.prisma.$queryRaw<
+ {
+ id: string;
+ duration: number;
+ }[]
+ >(
+ Prisma.sql`
+ SELECT
+ t.id,
+ o.duration
+ FROM
+ traces t
+ LEFT JOIN LATERAL (
+ SELECT
+ EXTRACT(epoch FROM COALESCE(max(o1.end_time), max(o1.start_time)))::double precision - EXTRACT(epoch FROM min(o1.start_time))::double precision AS duration
+ FROM
+ observations o1
+ WHERE
+ o1.project_id = t.project_id
+ AND o1.trace_id = t.id
+ GROUP BY
+ o1.project_id,
+ o1.trace_id) o ON TRUE
+ WHERE
+ t.project_id = ${input.projectId}
+ AND t.id = ANY(${traceIdsSQL})
+ `,
+ );
const items = runItems.map((ri) => {
return {