Skip to content

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

perf: improve trpc session.id performance (#5431)

Max Deichmann25bc0fc6600e
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index f1425070f3..0ec580da02 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -908,6 +908,7 @@ export const getObservationsGroupedByPromptName = async (
export const getCostForTraces = async (
projectId: string,
+ timestamp: Date,
traceIds: string[],
) => {
// Wrapping the query in a CTE allows us to skip FINAL which allows Clickhouse to use skip indexes.
@@ -917,6 +918,7 @@ export const getCostForTraces = async (
FROM observations o
WHERE o.project_id = {projectId: String}
AND o.trace_id IN ({traceIds: Array(String)})
+ AND o.start_time >= {timestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}
ORDER BY o.event_ts DESC
LIMIT 1 BY o.id, o.project_id
)
@@ -930,6 +932,7 @@ export const getCostForTraces = async (
params: {
projectId,
traceIds,
+ timestamp: convertDateToClickhouseDateTime(timestamp),
},
});
return res.length > 0 ? Number(res[0].total_cost) : undefined;
diff --git a/web/src/__tests__/async/sessions-trpc.servertest.ts b/web/src/__tests__/async/sessions-trpc.servertest.ts
new file mode 100644
index 0000000000..6820dcd127
--- /dev/null
+++ b/web/src/__tests__/async/sessions-trpc.servertest.ts
@@ -0,0 +1,131 @@
+/** @jest-environment node */
+/* eslint-disable @typescript-eslint/no-unsafe-member-access */
+
+import type { Session } from "next-auth";
+import { pruneDatabase } from "@/src/__tests__/test-utils";
+import { prisma } from "@langfuse/shared/src/db";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import {
+ createObservation,
+ createObservationsCh,
+ createTrace,
+ createTracesCh,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+
+describe("traces trps", () => {
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+ beforeEach(async () => await pruneDatabase());
+
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: "user-1",
+ canCreateOrganizations: true,
+ name: "Demo User",
+ organizations: [
+ {
+ id: "seed-org-id",
+ name: "Test Organization",
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ projects: [
+ {
+ id: projectId,
+ role: "ADMIN",
+ retentionDays: 30,
+ deletedAt: null,
+ name: "Test Project",
+ },
+ ],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ },
+ admin: true,
+ },
+ environment: {} as any,
+ };
+
+ const ctx = createInnerTRPCContext({ session });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+
+ describe("sessions.byId", () => {
+ it("access private session", async () => {
+ const sessionId = randomUUID();
+
+ await prisma.traceSession.create({
+ data: {
+ id: sessionId,
+ projectId,
+ },
+ });
+
+ const trace = createTrace({
+ project_id: projectId,
+ session_id: sessionId,
+ });
+
+ const trace2 = createTrace({
+ project_id: projectId,
+ session_id: sessionId,
+ });
+
+ await createTracesCh([trace, trace2]);
+
+ const observation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ });
+
+ const observation2 = createObservation({
+ project_id: projectId,
+ trace_id: trace2.id,
+ });
+
+ const observation3 = createObservation({
+ project_id: projectId,
+ trace_id: trace2.id,
+ });
+
+ await createObservationsCh([observation, observation2, observation3]);
+
+ const sessionRes = await caller.sessions.byId({
+ projectId,
+ sessionId,
+ });
+
+ expect(sessionRes).toEqual({
+ id: sessionId,
+ createdAt: expect.any(Date),
+ updatedAt: expect.any(Date),
+ projectId: projectId,
+ bookmarked: false,
+ public: false,
+ traces: expect.arrayContaining([
+ expect.objectContaining({
+ id: trace.id,
+ userId: trace.user_id,
+ name: trace.name,
+ timestamp: new Date(trace.timestamp),
+ scores: [],
+ }),
+ expect.objectContaining({
+ id: trace2.id,
+ userId: trace2.user_id,
+ name: trace2.name,
+ timestamp: new Date(trace2.timestamp),
+ scores: [],
+ }),
+ ]),
+ totalCost: expect.any(Number),
+ users: expect.arrayContaining([trace.user_id, trace2.user_id]),
+ });
+ });
+ });
+});
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 88166e61cf..2125824772 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -31,6 +31,7 @@ import {
logger,
getSessionsWithMetrics,
} from "@langfuse/shared/src/server";
+import { chunk } from "lodash";
const SessionFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -276,25 +277,30 @@ export const sessionRouter = createTRPCRouter({
input.sessionId,
);
- const traceIds = clickhouseTraces.map((t) => t.id);
- const chunkSize = 500;
- const chunks = [];
-
- for (let i = 0; i < traceIds.length; i += chunkSize) {
- chunks.push(traceIds.slice(i, i + chunkSize));
- }
+ const chunks = chunk(clickhouseTraces, 500);
+ // in the below queries, take the lowest timestamp as a filter condition
+ // to improve performance
const [scores, costs] = await Promise.all([
Promise.all(
chunks.map((chunk) =>
getScoresForTraces({
projectId: input.projectId,
- traceIds: chunk,
+ traceIds: chunk.map((t) => t.id),
+ timestamp: new Date(
+ Math.min(...chunk.map((t) => t.timestamp.getTime())),
+ ),
}),
),
).then((results) => results.flat()),
Promise.all(
- chunks.map((chunk) => getCostForTraces(input.projectId, chunk)),
+ chunks.map((chunk) =>
+ getCostForTraces(
+ input.projectId,
+ new Date(Math.min(...chunk.map((t) => t.timestamp.getTime()))),
+ chunk.map((t) => t.id),
+ ),
+ ),
).then((results) =>
results.reduce((sum, cost) => (sum ?? 0) + (cost ?? 0), 0),
),