🪢 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(eval): skip FINAL and unused aggregations in checkTraceExistsAndGetTimestamp (#13934)
Steffen Schmitz242e50ac1000
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 5059a86f6b..52ed286b1b 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -42,6 +42,9 @@ import { prisma } from "../../db";/*** Checks if trace exists in clickhouse.* Additionally, give back the timestamp of the trace as metadata.+ * Right now, this is only used for the evalService to decide whether a trace needs evaluation.+ * As LLMaaJ allows a reduced set of filters on observations, we exclude some expensive to compute+ * properties from the check. If those become used, we expect their absence to be caught by unit tests.** @param {string} projectId - Project ID for the trace* @param {string} traceId - ID of the trace to check@@ -112,12 +115,13 @@ export const checkTraceExistsAndGetTimestamp = async ({countIf(level = 'WARNING') as warning_count,countIf(level = 'DEFAULT') as default_count,countIf(level = 'DEBUG') as debug_count,- date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds,- sumMap(usage_details) as usage_details,- sumMap(cost_details) as cost_details,+ -- Remove those columns as this should only be used within the evalService and doesn't use them+ -- date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds,+ -- sumMap(usage_details) as usage_details,+ -- sumMap(cost_details) as cost_details,trace_id,project_id- FROM observations o FINAL+ FROM observations oWHERE o.project_id = {projectId: String}${timeStampFilter ? `AND o.start_time >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}AND o.start_time >= {timestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}@@ -159,7 +163,10 @@ export const checkTraceExistsAndGetTimestamp = async ({t.id as id,t.project_id as project_id,t.timestamp as timestamp- FROM traces t FINAL+ -- We skip FINAL here. If one trace exists that matches the conditions, we consider this truthy+ -- even if the trace got updated in the meantime to a non-matching state.+ -- As updates are usually addittive, this is deemed acceptable given the performance benefits.+ FROM traces t${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}WHERE ${tracesFilterRes.query}AND t.project_id = {projectId: String}diff --git a/web/src/__tests__/server/repositories/trace-repository.servertest.ts b/web/src/__tests__/server/repositories/trace-repository.servertest.tsindex 5879225414..47fbda58c7 100644--- a/web/src/__tests__/server/repositories/trace-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/trace-repository.servertest.ts@@ -398,75 +398,6 @@ describe("Clickhouse Traces Repository Test", () => {expect(exists).toBe(true);});- it.each([- {- name: "latency",- column: "latency",- observationOverrides: {- start_time: Date.now() - 15_000,- end_time: Date.now(),- },- matchingValue: 10,- nonMatchingValue: 20,- },- {- name: "totalCost",- column: "totalCost",- observationOverrides: {- cost_details: { input: 5, output: 10, total: 15 },- },- matchingValue: 10,- nonMatchingValue: 20,- },- ])(- "should check if trace exists with $name filter",- async ({- column,- observationOverrides,- matchingValue,- nonMatchingValue,- }) => {- const traceId = v4();- const trace = createTrace({ id: traceId, project_id: projectId });-- await createTracesCh([trace]);- await createObservationsCh([- createObservation({- trace_id: traceId,- project_id: projectId,- ...observationOverrides,- }),- ]);-- const { exists: shouldExist } = await checkTraceExistsAndGetTimestamp({- projectId,- traceId,- timestamp: new Date(),- filter: [- { type: "number", column, operator: ">", value: matchingValue },- ],- maxTimeStamp: undefined,- });- expect(shouldExist).toBe(true);-- const { exists: shouldNotExist } = await checkTraceExistsAndGetTimestamp({- projectId,- traceId,- timestamp: new Date(),- filter: [- {- type: "number",- column,- operator: ">",- value: nonMatchingValue,- },- ],- maxTimeStamp: undefined,- });- expect(shouldNotExist).toBe(false);- },- );-it("should handle timestamp filter in checkTraceExistsAndGetTimestamp", async () => {const traceId = v4();const trace = createTrace({diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.tsindex f17aa3f53b..4dceeec39b 100644--- a/worker/src/__tests__/evalService.test.ts+++ b/worker/src/__tests__/evalService.test.ts@@ -1253,113 +1253,6 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(jobs.length).toBe(0);}, 10_000);- test("cancels a job if the second event deselects", async () => {- const { projectId } = await createOrgProjectAndApiKey();- const traceId = randomUUID();-- await upsertTrace({- id: traceId,- project_id: projectId,- user_id: "a",- timestamp: convertDateToClickhouseDateTime(new Date()),- created_at: convertDateToClickhouseDateTime(new Date()),- updated_at: convertDateToClickhouseDateTime(new Date()),- });-- await prisma.llmApiKeys.create({- data: {- id: randomUUID(),- projectId,- secretKey: encrypt(String(OPENAI_API_KEY)),- provider: "openai",- adapter: LLMAdapter.OpenAI,- customModels: [],- displaySecretKey: "123456",- },- });-- const templateId = randomUUID();- await prisma.evalTemplate.create({- data: {- id: templateId,- projectId,- name: "test-template",- version: 1,- prompt: "Please evaluate toxicity {{input}} {{output}}",- model: "gpt-3.5-turbo",- provider: "openai",- modelParams: {},- outputDefinition: {- reasoning: "Please explain your reasoning",- score: "Please provide a score between 0 and 1",- },- },- });-- await prisma.jobConfiguration.create({- data: {- id: randomUUID(),- projectId,- filter: [- {- type: "string",- value: "a",- column: "User ID",- operator: "contains",- },- ],- jobType: "EVAL",- delay: 0,- sampling: new Decimal("1"),- targetObject: EvalTargetObject.TRACE,- scoreName: "score",- variableMapping: JSON.parse("[]"),- evalTemplateId: templateId,- },- });-- const payload = {- projectId,- traceId: traceId,- };-- await createEvalJobs({- sourceEventType: "trace-upsert",- event: payload,- jobTimestamp,- });-- // Wait for .5s- await new Promise((resolve) => setTimeout(resolve, 500));-- // update the trace to deselect the trace- await upsertTrace({- id: traceId,- project_id: projectId,- user_id: "b",- timestamp: convertDateToClickhouseDateTime(new Date()),- created_at: convertDateToClickhouseDateTime(new Date()),- updated_at: convertDateToClickhouseDateTime(new Date()),- });-- await createEvalJobs({- sourceEventType: "trace-upsert",- event: payload,- jobTimestamp,- }); // calling it twice to check it is only generated once-- const jobs = await prisma.jobExecution.findMany({- where: { projectId },- });-- expect(jobs.length).toBe(1);- expect(jobs[0].projectId).toBe(projectId);- expect(jobs[0].jobInputTraceId).toBe(traceId);- expect(jobs[0].status.toString()).toBe("CANCELLED");- expect(jobs[0].startTime).not.toBeNull();- expect(jobs[0].endTime).not.toBeNull();- }, 10_000);-test("does not create eval job for existing traces if time scope is EXISTING but handler enforces NEW only", async () => {const { projectId } = await createOrgProjectAndApiKey();const traceId = randomUUID();