🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
perf: remove redundant trace fetch for traces.byIdWithObservationsAndScores (#6548)
Steffen Schmitz2d1f104a1c3d
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 8575d0a55e..0844c2ee53 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -302,17 +302,27 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({return Number(rows[0]?.count ?? 0);};-export const getTraceById = async (- traceId: string,- projectId: string,- timestamp?: Date,-) => {+/**+ * Retrieves a trace record by its ID and associated project ID, with optional filtering by timestamp range.+ */+export const getTraceById = async ({+ traceId,+ projectId,+ timestamp,+ fromTimestamp,+}: {+ traceId: string;+ projectId: string;+ timestamp?: Date;+ fromTimestamp?: Date;+}) => {const query = `SELECT *FROM tracesWHERE id = {traceId: String}AND project_id = {projectId: String}${timestamp ? `AND toDate(timestamp) = toDate({timestamp: DateTime64(3)})` : ""}+ ${fromTimestamp ? `AND timestamp >= {fromTimestamp: DateTime64(3)}` : ""}ORDER BY event_ts DESCLIMIT 1`;@@ -325,6 +335,9 @@ export const getTraceById = async (...(timestamp? { timestamp: convertDateToClickhouseDateTime(timestamp) }: {}),+ ...(fromTimestamp+ ? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }+ : {}),},tags: {feature: "tracing",diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.tsindex 8483da46a0..df8d8f2d07 100644--- a/web/src/__e2e__/api.servertest.ts+++ b/web/src/__e2e__/api.servertest.ts@@ -111,7 +111,7 @@ describe("Ingestion Pipeline", () => {expect(traceResponse.body).not.toBeNull();expect((await traceResponse.json()).id).toBe(traceId);- const trace = await getTraceById(traceId, projectId);+ const trace = await getTraceById({ traceId, projectId });expect(trace).not.toBeNull();expect(trace?.name).toBe("test trace");diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.tsindex 32aab03b79..a6ae2fba26 100644--- a/web/src/__tests__/async/ingestion-api.servertest.ts+++ b/web/src/__tests__/async/ingestion-api.servertest.ts@@ -94,7 +94,7 @@ describe("/api/public/ingestion API Endpoint", () => {expect(response.status).toBe(207);await waitForExpect(async () => {- const trace = await getTraceById(entity.body.id, projectId);+ const trace = await getTraceById({ traceId: entity.body.id, projectId });expect(trace).toBeDefined();expect(trace!.id).toBe(entity.body.id);expect(trace!.projectId).toBe(projectId);@@ -128,7 +128,7 @@ describe("/api/public/ingestion API Endpoint", () => {//// expect(response.status).toBe(207);// await waitForExpect(async () => {- // const trace = await getTraceById(entity.body.id, projectId);+ // const trace = await getTraceById({ traceId: entity.body.id, projectId });// expect(trace).toBeDefined();// expect(trace!.id).toBe(entity.body.id);// expect(trace!.projectId).toBe(projectId);@@ -330,7 +330,7 @@ describe("/api/public/ingestion API Endpoint", () => {expect(response.status).toBe(207);await waitForExpect(async () => {- const trace = await getTraceById(`${traceId}-${char}-test`, projectId);+ const trace = await getTraceById({ traceId: `${traceId}-${char}-test`, projectId });expect(trace).toBeDefined();expect(trace!.id).toBe(`${traceId}-${char}-test`);expect(trace!.projectId).toBe(projectId);@@ -526,7 +526,7 @@ describe("/api/public/ingestion API Endpoint", () => {expect(response.status).toBe(207);await waitForExpect(async () => {- const trace = await getTraceById(traceId, projectId);+ const trace = await getTraceById({ traceId, projectId });expect(trace).toBeDefined();expect(trace!.id).toBe(traceId);expect(JSON.stringify(trace!.metadata)).toBe(diff --git a/web/src/__tests__/async/repositories/trace-repository.servertest.ts b/web/src/__tests__/async/repositories/trace-repository.servertest.tsindex 8926c72430..608bed840e 100644--- a/web/src/__tests__/async/repositories/trace-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/trace-repository.servertest.ts@@ -16,7 +16,7 @@ describe("Clickhouse Traces Repository Test", () => {});it("should throw if no traces are found", async () => {- expect(await getTraceById(v4(), v4())).toBeUndefined();+ expect(await getTraceById({ traceId: v4(), projectId: v4() })).toBeUndefined();});it("should return a trace if it exists", async () => {@@ -51,11 +51,11 @@ describe("Clickhouse Traces Repository Test", () => {await createTracesCh([trace]);- const result = await getTraceById(+ const result = await getTraceById({traceId,projectId,- new Date(trace.timestamp),- );+ timestamp: new Date(trace.timestamp),+ });expect(result).not.toBeNull();if (!result) {return;@@ -102,7 +102,7 @@ describe("Clickhouse Traces Repository Test", () => {await createTracesCh([trace]);- const result = await getTraceById(traceId, projectId);+ const result = await getTraceById({ traceId, projectId });expect(result).not.toBeNull();if (!result) {return;diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex 043bef0b45..756c38993a 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -435,7 +435,7 @@ describe("/api/public/traces API Endpoint", () => {// Thenexpect(deleteResponse.status).toBe(200);await waitForExpect(async () => {- const trace = await getTraceById(createdTrace.id, projectId);+ const trace = await getTraceById({ traceId: createdTrace.id, projectId });expect(trace).toBeUndefined();}, 10_000);}, 10_000);@@ -465,9 +465,9 @@ describe("/api/public/traces API Endpoint", () => {// Thenexpect(deleteResponse.status).toBe(200);await waitForExpect(async () => {- const trace1 = await getTraceById(createdTrace1.id, projectId);+ const trace1 = await getTraceById({ traceId: createdTrace1.id, projectId });expect(trace1).toBeUndefined();- const trace2 = await getTraceById(createdTrace2.id, projectId);+ const trace2 = await getTraceById({ traceId: createdTrace2.id, projectId });expect(trace2).toBeUndefined();}, 40_000);}, 60_000);diff --git a/web/src/features/comments/validateCommentReferenceObject.ts b/web/src/features/comments/validateCommentReferenceObject.tsindex cc96d4a222..8011794aa9 100644--- a/web/src/features/comments/validateCommentReferenceObject.ts+++ b/web/src/features/comments/validateCommentReferenceObject.ts@@ -23,7 +23,10 @@ export const validateCommentReferenceObject = async ({if (objectType === CommentObjectType.OBSERVATION) {clickhouseObject = await getObservationById(objectId, projectId);} else {- clickhouseObject = await getTraceById(objectId, projectId);+ clickhouseObject = await getTraceById({+ traceId: objectId,+ projectId,+ });}return !!clickhouseObjectdiff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].tsindex 21ce5cfa5e..30ad9007a1 100644--- a/web/src/pages/api/public/traces/[traceId].ts+++ b/web/src/pages/api/public/traces/[traceId].ts@@ -32,7 +32,10 @@ export default withMiddlewares({responseSchema: GetTraceV1Response,fn: async ({ query, auth }) => {const { traceId } = query;- const trace = await getTraceById(traceId, auth.scope.projectId);+ const trace = await getTraceById({+ traceId,+ projectId: auth.scope.projectId,+ });const [observations, scores] = await Promise.all([getObservationsForTrace(traceId,diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 374598b71c..b2f80c01b7 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -270,10 +270,10 @@ export const scoresRouter = createTRPCRouter({scope: "scores:CUD",});- const clickhouseTrace = await getTraceById(- input.traceId,- input.projectId,- );+ const clickhouseTrace = await getTraceById({+ traceId: input.traceId,+ projectId: input.projectId,+ });if (!clickhouseTrace) {logger.error(diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex a4d81e6250..32470f6135 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -181,6 +181,7 @@ export const traceRouter = createTRPCRouter({traceId: z.string(), // used for security checkprojectId: z.string(), // used for security checktimestamp: z.date().nullish(), // timestamp of the trace. Used to query CH more efficiently+ fromTimestamp: z.date().nullish(), // min timestamp of the trace. Used to query CH more efficiently}),).query(async ({ ctx }) => {@@ -195,29 +196,25 @@ export const traceRouter = createTRPCRouter({z.object({traceId: z.string(), // used for security checktimestamp: z.date().nullish(), // timestamp of the trace. Used to query CH more efficiently+ fromTimestamp: z.date().nullish(), // min timestamp of the trace. Used to query CH more efficientlyprojectId: z.string(), // used for security check}),)- .query(async ({ input }) => {- const [trace, observations, scores] = await Promise.all([- getTraceById(- input.traceId,- input.projectId,- input.timestamp ?? undefined,- ),+ .query(async ({ input, ctx }) => {+ const [observations, scores] = await Promise.all([getObservationsForTrace(input.traceId,input.projectId,- input.timestamp ?? undefined,+ input.timestamp ?? input.fromTimestamp ?? undefined,),getScoresForTraces({projectId: input.projectId,traceIds: [input.traceId],- timestamp: input.timestamp ?? undefined,+ timestamp: input.timestamp ?? input.fromTimestamp ?? undefined,}),]);- if (!trace) {+ if (!ctx.trace) {throw new TRPCError({code: "NOT_FOUND",message: "Trace not found",@@ -248,9 +245,9 @@ export const traceRouter = createTRPCRouter({: undefined;return {- ...trace,- input: trace.input ? JSON.stringify(trace.input) : null,- output: trace.output ? JSON.stringify(trace.output) : null,+ ...ctx.trace,+ input: ctx.trace.input ? JSON.stringify(ctx.trace.input) : null,+ output: ctx.trace.output ? JSON.stringify(ctx.trace.output) : null,scores: validatedScores,latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,observations: observations.map((o) => ({@@ -347,10 +344,10 @@ export const traceRouter = createTRPCRouter({let trace;- const clickhouseTrace = await getTraceById(- input.traceId,- input.projectId,- );+ const clickhouseTrace = await getTraceById({+ traceId: input.traceId,+ projectId: input.projectId,+ });if (clickhouseTrace) {trace = clickhouseTrace;clickhouseTrace.bookmarked = input.bookmarked;@@ -392,10 +389,10 @@ export const traceRouter = createTRPCRouter({after: input.public,});- const clickhouseTrace = await getTraceById(- input.traceId,- input.projectId,- );+ const clickhouseTrace = await getTraceById({+ traceId: input.traceId,+ projectId: input.projectId,+ });if (!clickhouseTrace) {logger.error(`Trace not found in Clickhouse: ${input.traceId}. Skipping publishing.`,@@ -438,10 +435,10 @@ export const traceRouter = createTRPCRouter({after: input.tags,});- const clickhouseTrace = await getTraceById(- input.traceId,- input.projectId,- );+ const clickhouseTrace = await getTraceById({+ traceId: input.traceId,+ projectId: input.projectId,+ });if (!clickhouseTrace) {logger.error(`Trace not found in Clickhouse: ${input.traceId}. Skipping tag update.`,diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex e5f59dc99a..68db10f2d7 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -335,6 +335,7 @@ const inputTraceSchema = z.object({traceId: z.string(),projectId: z.string(),timestamp: z.date().nullish(),+ fromTimestamp: z.date().nullish(),});const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {@@ -351,8 +352,14 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {const traceId = result.data.traceId;const projectId = result.data.projectId;const timestamp = result.data.timestamp;+ const fromTimestamp = result.data.fromTimestamp;- const trace = await getTraceById(traceId, projectId, timestamp ?? undefined);+ const trace = await getTraceById({+ traceId,+ projectId,+ timestamp: timestamp ?? undefined,+ fromTimestamp: fromTimestamp ?? undefined,+ });if (!trace) {logger.error(`Trace with id ${traceId} not found for project ${projectId}`);diff --git a/worker/src/__tests__/dataRetentionProcessing.test.ts b/worker/src/__tests__/dataRetentionProcessing.test.tsindex d032d3bd5b..7b66b233b4 100644--- a/worker/src/__tests__/dataRetentionProcessing.test.ts+++ b/worker/src/__tests__/dataRetentionProcessing.test.ts@@ -270,9 +270,9 @@ describe("DataRetentionProcessingJob", () => {} as Job);// Then- const traceOld = await getTraceById(`${baseId}-trace-old`, projectId);+ const traceOld = await getTraceById({ traceId: `${baseId}-trace-old`, projectId });expect(traceOld).toBeUndefined();- const traceNew = await getTraceById(`${baseId}-trace-new`, projectId);+ const traceNew = await getTraceById({ traceId: `${baseId}-trace-new`, projectId });expect(traceNew).toBeDefined();});diff --git a/worker/src/__tests__/projectDeletionProcessing.test.ts b/worker/src/__tests__/projectDeletionProcessing.test.tsindex 35f16a0958..bc71a17ea3 100644--- a/worker/src/__tests__/projectDeletionProcessing.test.ts+++ b/worker/src/__tests__/projectDeletionProcessing.test.ts@@ -135,7 +135,7 @@ describe("ProjectDeletionProcessingJob", () => {} as Job);// Then- const trace = await getTraceById(`${baseId}-trace`, projectId);+ const trace = await getTraceById({ traceId: `${baseId}-trace`, projectId });expect(trace).toBeUndefined();expect(() =>getObservationById(`${baseId}-observation`, projectId),diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.tsindex dc8bf3233f..a1457ffeec 100644--- a/worker/src/ee/evaluation/evalService.ts+++ b/worker/src/ee/evaluation/evalService.ts@@ -709,7 +709,7 @@ export async function extractVariablesFromTracingData({return { var: variable, value: "" };}- const trace = await getTraceById(traceId, projectId);+ const trace = await getTraceById({ traceId, projectId });// user facing errorsif (!trace) {