🪢 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: improve dataset run item performance (#4514)
Max Deichmannd821423c6a7e
diff --git a/web/src/features/datasets/components/DatasetRunsTable.tsx b/web/src/features/datasets/components/DatasetRunsTable.tsxindex 62f6b3478d..c1e367dd53 100644--- a/web/src/features/datasets/components/DatasetRunsTable.tsx+++ b/web/src/features/datasets/components/DatasetRunsTable.tsx@@ -34,16 +34,18 @@ import { Checkbox } from "@/src/components/ui/checkbox";import { type RowSelectionState } from "@tanstack/react-table";import Link from "next/link";import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";+import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";+import { Skeleton } from "@/src/components/ui/skeleton";export type DatasetRunRowData = {id: string;name: string;createdAt: string;countRunItems: string;- avgLatency: number;- avgTotalCost: string;+ avgLatency: number | undefined;+ avgTotalCost: string | undefined;// scores holds grouped column with individual scores- scores?: ScoreAggregate;+ scores?: ScoreAggregate | undefined;description: string;metadata: Prisma.JsonValue;};@@ -110,6 +112,25 @@ export function DatasetRunsTable(props: {limit: paginationState.pageSize,queryClickhouse: useClickhouse(),});++ const runsMetrics = api.datasets.runsByDatasetIdMetrics.useQuery({+ projectId: props.projectId,+ datasetId: props.datasetId,+ page: paginationState.pageIndex,+ limit: paginationState.pageSize,+ queryClickhouse: useClickhouse(),+ });++ type DatasetsCoreOutput =+ RouterOutput["datasets"]["runsByDatasetId"]["runs"][number];+ type DatasetsMetricOutput =+ RouterOutput["datasets"]["runsByDatasetIdMetrics"]["runs"][number];++ const runsWithMetrics = joinTableCoreAndMetrics<+ DatasetsCoreOutput,+ DatasetsMetricOutput+ >(runs.data?.runs, runsMetrics.data?.runs);+const { setDetailPageList } = useDetailPageLists();useEffect(() => {if (runs.isSuccess) {@@ -225,6 +246,7 @@ export function DatasetRunsTable(props: {cell: ({ row }) => {const avgLatency: DatasetRunRowData["avgLatency"] =row.getValue("avgLatency");+ if (avgLatency === undefined) return <Skeleton className="h-3 w-1/2" />;return <>{formatIntervalSeconds(avgLatency)}</>;},},@@ -237,6 +259,7 @@ export function DatasetRunsTable(props: {cell: ({ row }) => {const avgTotalCost: DatasetRunRowData["avgTotalCost"] =row.getValue("avgTotalCost");+ if (!avgTotalCost) return <Skeleton className="h-3 w-1/2" />;return <>{avgTotalCost}</>;},},@@ -301,11 +324,12 @@ export function DatasetRunsTable(props: {createdAt: item.createdAt.toLocaleString(),countRunItems: item.countRunItems.toString(),avgLatency: item.avgLatency,- avgTotalCost: usdFormatter(item.avgTotalCost.toNumber()),- scores: verifyAndPrefixScoreDataAgainstKeys(- scoreKeysAndProps,- item.scores,- ),+ avgTotalCost: item.avgTotalCost+ ? usdFormatter(item.avgTotalCost.toNumber())+ : undefined,+ scores: item.scores+ ? verifyAndPrefixScoreDataAgainstKeys(scoreKeysAndProps, item.scores)+ : undefined,description: item.description ?? "",metadata: item.metadata,};@@ -362,7 +386,9 @@ export function DatasetRunsTable(props: {: {isLoading: false,isError: false,- data: runs.data.runs.map((t) => convertToTableRow(t)),+ data: (runsWithMetrics.rows ?? []).map((t) =>+ convertToTableRow(t),+ ),}}pagination={{diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.tsindex 9fecdde17d..d40759f267 100644--- a/web/src/features/datasets/server/dataset-router.ts+++ b/web/src/features/datasets/server/dataset-router.ts@@ -13,6 +13,8 @@ import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAcimport { auditLog } from "@/src/features/audit-logs/auditLog";import { DB } from "@/src/server/db";import {+ type PrismaClient,+ type ScoreAggregate,type ScoreSimplified,filterAndValidateDbScoreList,paginationZod,@@ -21,6 +23,7 @@ import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";import {createDatasetRunsTable,+ createDatasetRunsTableWithoutMetrics,datasetRunsTableSchema,fetchDatasetItems,getRunItemsByRunIdOrItemId,@@ -165,132 +168,14 @@ export const datasetRouter = createTRPCRouter({operation: "datasets.runsByDatasetId",user: ctx.session.user,pgExecution: async () => {- const scoresByRunId = await ctx.prisma.$queryRaw<- Array<{ scores: Array<ScoreSimplified>; runId: string }>- >(Prisma.sql`- SELECT- runs.id "runId",- array_agg(s.score) AS "scores"- FROM- dataset_runs runs- JOIN datasets ON datasets.id = runs.dataset_id AND datasets.project_id = ${input.projectId}- LEFT JOIN LATERAL (- SELECT- jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"- FROM- dataset_run_items ri- JOIN scores s- ON s.trace_id = ri.trace_id- AND (ri.observation_id IS NULL OR s.observation_id = ri.observation_id)- AND s.project_id = ${input.projectId}- JOIN traces t ON t.id = s.trace_id AND t.project_id = ${input.projectId}- WHERE- ri.project_id = ${input.projectId}- AND ri.dataset_run_id = runs.id- ) s ON true- WHERE- runs.dataset_id = ${input.datasetId}- AND runs.project_id = ${input.projectId}- AND s.score IS NOT NULL- GROUP BY- runs.id- LIMIT ${input.limit}- OFFSET ${input.page * input.limit}- `);+ return await runsByDatasetIdPg(ctx.prisma, input);+ },+ clickhouseExecution: async () => {+ // we cannot easily join all the tracing data with the dataset run items+ // hence, we pull the trace_ids and observation_ids separately for all run items+ // afterwards, we aggregate them per run- const runs = await ctx.prisma.$queryRaw<- Array<- DatasetRuns & {- avgLatency: number;- avgTotalCost: Prisma.Decimal;- countRunItems: number;- }- >- >(Prisma.sql`- SELECT- runs.id,- runs.name,- runs.description,- runs.metadata,- runs.created_at "createdAt",- runs.updated_at "updatedAt",- COALESCE(o_latency_and_total_cost. "o_avgLatency", t_latency_and_total_cost."t_avgLatency", 0) "avgLatency",- COALESCE(o_latency_and_total_cost. "o_avgTotalCost", t_latency_and_total_cost."t_avgTotalCost", 0) "avgTotalCost",- COALESCE(run_items_count.count, 0)::int "countRunItems"- FROM- dataset_runs runs- JOIN datasets ON datasets.id = runs.dataset_id- AND datasets.project_id = ${input.projectId}-- -- Add average latency and cost if a run's items are linked to observations- -- LIMITATION: this will only work if all items for a given run are linked to either observations or traces- -- If a run has items linked to both observations and traces, the average latency and cost will be incorrect as only those from the observations will be used- LEFT JOIN LATERAL (- SELECT- AVG(o.latency) AS "o_avgLatency",- AVG(COALESCE(o.calculated_total_cost, 0)) AS "o_avgTotalCost"- FROM- dataset_run_items ri- JOIN observations_view o ON o.id = ri.observation_id- AND o.project_id = ${input.projectId}- WHERE- ri.project_id = ${input.projectId}- AND ri.dataset_run_id = runs.id) o_latency_and_total_cost ON TRUE-- -- Add average latency and cost if run's items are linked to traces- LEFT JOIN LATERAL (- -- Average across run items. One run has many items- SELECT- AVG(trace_latency_cost.duration) AS "t_avgLatency",- AVG(trace_latency_cost.total_cost) AS "t_avgTotalCost"- FROM- dataset_run_items ri- LEFT JOIN LATERAL (- -- Latency and cost for a run item's trace- SELECT- t.id,- o.duration,- o.total_cost- FROM- traces t- LEFT JOIN LATERAL (- -- Latency and cost across a trace's observations- 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,- SUM(COALESCE(o1.calculated_total_cost, 0)) AS total_cost- FROM- -- Use observations_view as cost are not backfilled for self-hosters. Once V3 is migration is done, we can use observations instead- observations_view o1- WHERE- o1.project_id = ${input.projectId}- 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 = ri.trace_id) trace_latency_cost ON TRUE- WHERE- ri.project_id = ${input.projectId}- AND ri.dataset_run_id = runs.id) t_latency_and_total_cost ON TRUE-- -- Add run item counts- LEFT JOIN LATERAL (- SELECT- count(*) AS count- FROM- dataset_run_items ri- WHERE- ri.dataset_run_id = runs.id- AND ri.project_id = ${input.projectId}) run_items_count ON TRUE- WHERE- runs.dataset_id = ${input.datasetId}- AND runs.project_id = ${input.projectId}- ORDER BY- runs.created_at DESC- LIMIT ${input.limit}- OFFSET ${input.page * input.limit}- `);+ const runs = await createDatasetRunsTableWithoutMetrics(input);const totalRuns = await ctx.prisma.datasetRuns.count({where: {@@ -301,16 +186,21 @@ export const datasetRouter = createTRPCRouter({return {totalRuns,- runs: runs.map((run) => ({- ...run,- scores: aggregateScores(- scoresByRunId.flatMap((s) =>- s.runId === run.id ? s.scores : [],- ),- ),- })),+ runs,};},+ });+ }),+ runsByDatasetIdMetrics: protectedProjectProcedure+ .input(datasetRunsTableSchema)+ .query(async ({ input, ctx }) => {+ return await measureAndReturnApi({+ input,+ operation: "datasets.runsByDatasetId",+ user: ctx.session.user,+ pgExecution: async () => {+ return await runsByDatasetIdPg(ctx.prisma, input);+ },clickhouseExecution: async () => {// we cannot easily join all the tracing data with the dataset run items// hence, we pull the trace_ids and observation_ids separately for all run items@@ -961,3 +851,158 @@ export const datasetRouter = createTRPCRouter({return deletedDatasetRun;}),});++async function runsByDatasetIdPg(+ prisma: PrismaClient,+ input: {+ projectId: string;+ datasetId: string;+ queryClickhouse: boolean;+ page: number;+ limit: number;+ },+) {+ const scoresByRunId = await prisma.$queryRaw<+ Array<{ scores: Array<ScoreSimplified>; runId: string }>+ >(Prisma.sql`+ SELECT+ runs.id "runId",+ array_agg(s.score) AS "scores"+ FROM+ dataset_runs runs+ JOIN datasets ON datasets.id = runs.dataset_id AND datasets.project_id = ${input.projectId}+ LEFT JOIN LATERAL (+ SELECT+ jsonb_build_object ('name', s.name, 'stringValue', s.string_value, 'value', s.value, 'source', s."source", 'dataType', s.data_type, 'comment', s.comment) AS "score"+ FROM+ dataset_run_items ri+ JOIN scores s+ ON s.trace_id = ri.trace_id+ AND (ri.observation_id IS NULL OR s.observation_id = ri.observation_id)+ AND s.project_id = ${input.projectId}+ JOIN traces t ON t.id = s.trace_id AND t.project_id = ${input.projectId}+ WHERE+ ri.project_id = ${input.projectId}+ AND ri.dataset_run_id = runs.id+ ) s ON true+ WHERE+ runs.dataset_id = ${input.datasetId}+ AND runs.project_id = ${input.projectId}+ AND s.score IS NOT NULL+ GROUP BY+ runs.id+ LIMIT ${input.limit}+ OFFSET ${input.page * input.limit}+ `);++ const runs = await prisma.$queryRaw<+ Array<+ DatasetRuns & {+ avgLatency: number | undefined;+ avgTotalCost: Prisma.Decimal | undefined;+ countRunItems: number;+ }+ >+ >(Prisma.sql`+ SELECT+ runs.id,+ runs.name,+ runs.description,+ runs.metadata,+ runs.created_at "createdAt",+ runs.updated_at "updatedAt",+ COALESCE(o_latency_and_total_cost. "o_avgLatency", t_latency_and_total_cost."t_avgLatency", 0) "avgLatency",+ COALESCE(o_latency_and_total_cost. "o_avgTotalCost", t_latency_and_total_cost."t_avgTotalCost", 0) "avgTotalCost",+ COALESCE(run_items_count.count, 0)::int "countRunItems"+ FROM+ dataset_runs runs+ JOIN datasets ON datasets.id = runs.dataset_id+ AND datasets.project_id = ${input.projectId}++ -- Add average latency and cost if a run's items are linked to observations+ -- LIMITATION: this will only work if all items for a given run are linked to either observations or traces+ -- If a run has items linked to both observations and traces, the average latency and cost will be incorrect as only those from the observations will be used+ LEFT JOIN LATERAL (+ SELECT+ AVG(o.latency) AS "o_avgLatency",+ AVG(COALESCE(o.calculated_total_cost, 0)) AS "o_avgTotalCost"+ FROM+ dataset_run_items ri+ JOIN observations_view o ON o.id = ri.observation_id+ AND o.project_id = ${input.projectId}+ WHERE+ ri.project_id = ${input.projectId}+ AND ri.dataset_run_id = runs.id) o_latency_and_total_cost ON TRUE++ -- Add average latency and cost if run's items are linked to traces+ LEFT JOIN LATERAL (+ -- Average across run items. One run has many items+ SELECT+ AVG(trace_latency_cost.duration) AS "t_avgLatency",+ AVG(trace_latency_cost.total_cost) AS "t_avgTotalCost"+ FROM+ dataset_run_items ri+ LEFT JOIN LATERAL (+ -- Latency and cost for a run item's trace+ SELECT+ t.id,+ o.duration,+ o.total_cost+ FROM+ traces t+ LEFT JOIN LATERAL (+ -- Latency and cost across a trace's observations+ 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,+ SUM(COALESCE(o1.calculated_total_cost, 0)) AS total_cost+ FROM+ -- Use observations_view as cost are not backfilled for self-hosters. Once V3 is migration is done, we can use observations instead+ observations_view o1+ WHERE+ o1.project_id = ${input.projectId}+ 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 = ri.trace_id) trace_latency_cost ON TRUE+ WHERE+ ri.project_id = ${input.projectId}+ AND ri.dataset_run_id = runs.id) t_latency_and_total_cost ON TRUE++ -- Add run item counts+ LEFT JOIN LATERAL (+ SELECT+ count(*) AS count+ FROM+ dataset_run_items ri+ WHERE+ ri.dataset_run_id = runs.id+ AND ri.project_id = ${input.projectId}) run_items_count ON TRUE+ WHERE+ runs.dataset_id = ${input.datasetId}+ AND runs.project_id = ${input.projectId}+ ORDER BY+ runs.created_at DESC+ LIMIT ${input.limit}+ OFFSET ${input.page * input.limit}+ `);++ const totalRuns = await prisma.datasetRuns.count({+ where: {+ datasetId: input.datasetId,+ projectId: input.projectId,+ },+ });++ return {+ totalRuns,+ runs: runs.map((run) => ({+ ...run,+ scores: aggregateScores(+ scoresByRunId.flatMap((s) => (s.runId === run.id ? s.scores : [])),+ ) as ScoreAggregate | undefined+ })),+ };+}diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.tsindex 4f7413e1bd..8bcc124d77 100644--- a/web/src/features/datasets/server/service.ts+++ b/web/src/features/datasets/server/service.ts@@ -53,6 +53,29 @@ type PostgresDatasetRun = {export type DatasetRunsTableInput = z.infer<typeof datasetRunsTableSchema>;+export const createDatasetRunsTableWithoutMetrics = async (+ input: DatasetRunsTableInput,+) => {+ const runs = await getDatasetRunsFromPostgres(input);++ return runs.map(({ run_items, ...run }) => ({+ ...run,+ projectId: input.projectId,+ datasetId: input.datasetId,+ id: run.run_id,+ countRunItems: run_items.length,+ name: run.run_name,+ description: run.run_description,+ metadata: run.run_metadata,+ createdAt: run.run_created_at,+ updatedAt: run.run_updated_at,+ // return metric fields as undefined+ avgTotalCost: undefined,+ avgLatency: undefined,+ scores: undefined,+ }));+};+// we might have many traces / observations in Postgres which belong to data in clickhouse.// We need to create a temp table in CH, dump the data in there, and then join in CH.export const createDatasetRunsTable = async (input: DatasetRunsTableInput) => {@@ -262,25 +285,22 @@ const getObservationLatencyAndCostForDataset = async (// the subquery here will improve performance as it allows clickhouse to use skip-indices on// the observations tableconst query = `- WITH agg AS (- SELECT- dateDiff('milliseconds', start_time, end_time) AS latency_ms,- total_cost AS cost,- run_id- FROM observations AS o- INNER JOIN ${tableName} AS tmp ON (o.id = tmp.observation_id) AND (o.project_id = tmp.project_id) AND (tmp.trace_id = o.trace_id)- WHERE (id, trace_id, project_id) IN (- SELECT- observation_id,- trace_id,- project_id- FROM ${tableName}- WHERE (project_id = {projectId: String}) AND (dataset_id = {datasetId: String}) AND (observation_id IS NOT NULL)- )- ORDER BY o.start_time DESC- LIMIT 1 BY- o.id,- o.project_id+ WITH agg AS (+ SELECT+ dateDiff('milliseconds', start_time, end_time) AS latency_ms,+ total_cost AS cost,+ run_id+ FROM observations AS o+ INNER JOIN ${tableName} AS tmp ON (o.id = tmp.observation_id) AND (o.project_id = tmp.project_id) AND (tmp.trace_id = o.trace_id)+ WHERE+ o.project_id = {projectId: String}+ AND (id, trace_id) IN (+ SELECT+ observation_id,+ trace_id+ FROM ${tableName}+ WHERE (project_id = {projectId: String}) AND (dataset_id = {datasetId: String}) AND (observation_id IS NOT NULL)+ ))SELECTrun_id,@@ -322,7 +342,7 @@ const getTraceLatencyAndCostForDataset = async (run_id,dateDiff('milliseconds', min(start_time), max(end_time)) AS latency_ms,sum(total_cost) AS cost- FROM observations o JOIN ${tableName} tmp+ FROM observations o JOIN ${tableName} tmpON tmp.project_id = o.project_idAND tmp.trace_id = o.trace_idWHERE o.project_id = {projectId: String}