🪢 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: use aggregations to calculate traces trpc all route (#8599)
Steffen Schmitzbabc02a067d1
diff --git a/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts b/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.tsindex 8a8fc2bd93..2a9098a1fd 100644--- a/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts@@ -8,6 +8,7 @@ type OrderByStateNotNull = Exclude<OrderByState, null>;export function orderByToClickhouseSql(orderBy: OrderByState | OrderByState[] = [],tableColumns: UiColumnMappings,+ usedInAggregation = false,): string {if (!orderBy ||@@ -44,9 +45,11 @@ export function orderByToClickhouseSql(throw new Error("Invalid order: " + ob.order);}+ const column = `${col.queryPrefix ? col.queryPrefix + "." : ""}${col.clickhouseSelect}`;+// Append the order by clause to the arrayorderByClauses.push(- `${col.queryPrefix ? col.queryPrefix + "." : ""}${col.clickhouseSelect} ${order.data}`,+ `${usedInAggregation ? `anyLast(${column})` : column} ${order.data}`,);}diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.tsindex 2fadf61518..410eb6efbb 100644--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts@@ -10,9 +10,10 @@ export const clickhouseSearchCondition = () => {const prefix = tablePrefix ? `${tablePrefix}.` : "";+ // We use a hard-coded prefix for user_id as it only occurs in the trace context.const conditions = [!searchType || searchType.includes("id")- ? `${prefix}id ILIKE {searchString: String} OR user_id ILIKE {searchString: String} OR ${prefix}name ILIKE {searchString: String}`+ ? `${prefix}id ILIKE {searchString: String} OR t.user_id ILIKE {searchString: String} OR ${prefix}name ILIKE {searchString: String}`: null,searchType && searchType.includes("content") && !useTracesAmtCompatMode? `${prefix}input ILIKE {searchString: String} OR ${prefix}output ILIKE {searchString: String}`diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex ba43c0ac06..bdbce1366b 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -1606,7 +1606,7 @@ export const getUserMetrics = async (${timestampFilter ? `AND o.start_time >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}AND o.trace_id in (SELECT distinct id- from __TRACE_TABLE__+ from __TRACE_TABLE__ twhereuser_id IN ({userIds: Array(String) })AND project_id = {projectId: String }diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex c65551bb47..7a808cebf4 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -363,15 +363,15 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {t.id as id,t.project_id as project_id,t.timestamp as timestamp,- os.latency_milliseconds / 1000 as latency,- os.cost_details as cost_details,- os.usage_details as usage_details,- os.aggregated_level as level,- os.error_count as error_count,- os.warning_count as warning_count,- os.default_count as default_count,- os.debug_count as debug_count,- os.observation_count as observation_count,+ o.latency_milliseconds / 1000 as latency,+ o.cost_details as cost_details,+ o.usage_details as usage_details,+ o.aggregated_level as level,+ o.error_count as error_count,+ o.warning_count as warning_count,+ o.default_count as default_count,+ o.debug_count as debug_count,+ o.observation_count as observation_count,s.scores_avg as scores_avg,s.score_categories as score_categories,t.public as public`;@@ -449,7 +449,7 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {SELECT ${sqlSelect}-- FINAL is used for non default ordering and count.FROM traces t ${["metrics", "rows", "identifiers"].includes(select) && defaultOrder ? "" : "FINAL"}- ${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats os on os.project_id = t.project_id and os.trace_id = t.id` : ""}+ ${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats o on o.project_id = t.project_id and o.trace_id = t.id` : ""}${select === "metrics" || requiresScoresJoin ? `LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id` : ""}WHERE t.project_id = {projectId: String}${tracesFilterRes ? `AND ${tracesFilterRes.query}` : ""}@@ -498,40 +498,40 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {sqlSelect = `t.id as id,t.project_id as project_id,- t.timestamp as timestamp,- os.latency_milliseconds / 1000 as latency,- os.cost_details as cost_details,- os.usage_details as usage_details,- os.aggregated_level as level,- os.error_count as error_count,- os.warning_count as warning_count,- os.default_count as default_count,- os.debug_count as debug_count,- os.observation_count as observation_count,- s.scores_avg as scores_avg,- s.score_categories as score_categories,- t.public as public`;+ min(t.timestamp) as timestamp,+ max(o.latency_milliseconds) / 1000 as latency,+ anyLast(o.cost_details) as cost_details,+ anyLast(o.usage_details) as usage_details,+ anyLast(o.aggregated_level) as level,+ anyLast(o.error_count) as error_count,+ anyLast(o.warning_count) as warning_count,+ anyLast(o.default_count) as default_count,+ anyLast(o.debug_count) as debug_count,+ anyLast(o.observation_count) as observation_count,+ anyLast(s.scores_avg) as scores_avg,+ anyLast(s.score_categories) as score_categories,+ argMaxMerge(t.public) as public`;break;case "rows":sqlSelect = `t.id as id,t.project_id as project_id,- t.timestamp as timestamp,- t.tags as tags,- finalizeAggregation(t.bookmarked) as bookmarked,- t.name as name,- t.release as release,- t.version as version,- t.user_id as user_id,- t.environment as environment,- t.session_id as session_id,- finalizeAggregation(t.public) as public`;+ min(t.timestamp) as timestamp,+ groupUniqArrayArray(t.tags) as tags,+ argMaxMerge(t.bookmarked) as bookmarked,+ anyLast(t.name) as name,+ anyLast(t.release) as release,+ anyLast(t.version) as version,+ anyLast(t.user_id) as user_id,+ anyLast(t.environment) as environment,+ anyLast(t.session_id) as session_id,+ argMaxMerge(t.public) as public`;break;case "identifiers":sqlSelect = `t.id as id,t.project_id as projectId,- t.timestamp as timestamp`;+ min(t.timestamp) as timestamp`;break;default:throw new Error(`Unknown select type: ${select}`);@@ -547,6 +547,7 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {const chOrderBy = orderByToClickhouseSql([orderBy ?? null].flat(),tracesTableUiColumnDefinitions,+ true,);const tracesAmt =@@ -558,12 +559,13 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {${observationsAndScoresCTE}SELECT ${sqlSelect}- FROM ${tracesAmt} t FINAL- ${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats os on os.project_id = t.project_id and os.trace_id = t.id` : ""}+ FROM ${tracesAmt} t+ ${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats o on o.project_id = t.project_id and o.trace_id = t.id` : ""}${select === "metrics" || requiresScoresJoin ? `LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id` : ""}WHERE t.project_id = {projectId: String}${tracesFilterRes ? `AND ${tracesFilterRes.query}` : ""}${search.query}+ GROUP BY project_id, id${chOrderBy}${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;diff --git a/packages/shared/src/tableDefinitions/mapTracesTable.ts b/packages/shared/src/tableDefinitions/mapTracesTable.tsindex 96abfbb1e5..80cf710e43 100644--- a/packages/shared/src/tableDefinitions/mapTracesTable.ts+++ b/packages/shared/src/tableDefinitions/mapTracesTable.ts@@ -13,6 +13,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [uiTableId: "level",clickhouseTableName: "observations",clickhouseSelect: "aggregated_level",+ queryPrefix: "o",},{uiTableName: "ID",@@ -25,85 +26,98 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [uiTableId: "name",clickhouseTableName: "traces",clickhouseSelect: "name",+ queryPrefix: "t",},{uiTableName: "Timestamp",uiTableId: "timestamp",clickhouseTableName: "traces",clickhouseSelect: "timestamp",+ queryPrefix: "t",},{uiTableName: "User ID",uiTableId: "userId",clickhouseTableName: "traces",clickhouseSelect: "user_id",+ queryPrefix: "t",},{uiTableName: "Session ID",uiTableId: "sessionId",clickhouseTableName: "traces",clickhouseSelect: "session_id",+ queryPrefix: "t",},{uiTableName: "Metadata",uiTableId: "metadata",clickhouseTableName: "traces",clickhouseSelect: "metadata",+ queryPrefix: "t",},{uiTableName: "Version",uiTableId: "version",clickhouseTableName: "traces",clickhouseSelect: "version",+ queryPrefix: "t",},{uiTableName: "Release",uiTableId: "release",clickhouseTableName: "traces",clickhouseSelect: "release",+ queryPrefix: "t",},{uiTableName: "Environment",uiTableId: "environment",clickhouseTableName: "traces",clickhouseSelect: "environment",+ queryPrefix: "t",},{uiTableName: "Tags",uiTableId: "tags",clickhouseTableName: "traces",clickhouseSelect: "tags",+ queryPrefix: "t",},{uiTableName: "Warning Level Count",uiTableId: "warningCount",clickhouseTableName: "observations",clickhouseSelect: "warning_count",+ queryPrefix: "o",},{uiTableName: "Error Level Count",uiTableId: "errorCount",clickhouseTableName: "observations",clickhouseSelect: "error_count",+ queryPrefix: "o",},{uiTableName: "Default Level Count",uiTableId: "defaultCount",clickhouseTableName: "observations",clickhouseSelect: "default_count",+ queryPrefix: "o",},{uiTableName: "Debug Level Count",uiTableId: "debugCount",clickhouseTableName: "observations",clickhouseSelect: "debug_count",+ queryPrefix: "o",},{uiTableName: "Input Tokens",uiTableId: "inputTokens",clickhouseTableName: "observations",clickhouseSelect:- "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))",+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, o.usage_details)))",clickhouseTypeOverwrite: "Decimal64(3)",},{@@ -111,7 +125,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [uiTableId: "outputTokens",clickhouseTableName: "observations",clickhouseSelect:- "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))",+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, o.usage_details)))",clickhouseTypeOverwrite: "Decimal64(3)",},{@@ -119,7 +133,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [uiTableId: "totalTokens",clickhouseTableName: "observations",clickhouseSelect:- "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",+ "if(mapExists((k, v) -> (k = 'total'), o.usage_details), o.usage_details['total'], NULL)",clickhouseTypeOverwrite: "Decimal64(3)",},{@@ -127,7 +141,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [uiTableId: "tokens",clickhouseTableName: "observations",clickhouseSelect:- "if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",+ "if(mapExists((k, v) -> (k = 'total'), o.usage_details), o.usage_details['total'], NULL)",clickhouseTypeOverwrite: "Decimal64(3)",},// Scores column duplicated to allow renaming column name. Will be removed once session storage cache is outdated@@ -154,6 +168,7 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [uiTableName: "Latency (s)",uiTableId: "latency",clickhouseTableName: "observations",+ queryPrefix: "o",clickhouseSelect: "latency_milliseconds / 1000",// If we use the default of Decimal64(12), we cannot filter for more than ~40min due to an overflowclickhouseTypeOverwrite: "Decimal64(3)",@@ -163,19 +178,20 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [uiTableId: "inputCost",clickhouseTableName: "observations",clickhouseSelect:- "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details)))",+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, o.cost_details)))",},{uiTableName: "Output Cost ($)",uiTableId: "outputCost",clickhouseTableName: "observations",clickhouseSelect:- "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details)))",+ "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, o.cost_details)))",},{uiTableName: "Total Cost ($)",uiTableId: "totalCost",clickhouseTableName: "observations",+ queryPrefix: "o",clickhouseSelect: "cost_details['total']",},];diff --git a/web/src/__tests__/async/traces-trpc.servertest.ts b/web/src/__tests__/async/traces-trpc.servertest.tsindex 85dabefd2b..1909184e8f 100644--- a/web/src/__tests__/async/traces-trpc.servertest.ts+++ b/web/src/__tests__/async/traces-trpc.servertest.ts@@ -52,6 +52,153 @@ describe("traces trpc", () => {const ctx = createInnerTRPCContext({ session });const caller = appRouter.createCaller({ ...ctx, prisma });+ describe("traces.all", () => {+ it("list traces for default view", async () => {+ const trace = createTrace({+ project_id: projectId,+ });++ await createTracesCh([trace]);++ const traces = await caller.traces.all({+ projectId,+ filter: [+ {+ column: "timestamp",+ type: "datetime",+ operator: ">=",+ value: new Date(new Date().getTime() - 1000).toISOString(),+ },+ ],+ searchQuery: null,+ searchType: ["id"],+ page: 0,+ limit: 50,+ orderBy: {+ column: "timestamp",+ order: "DESC",+ },+ });++ expect(traces.traces.length).toBeGreaterThan(0);+ });++ it("list traces with custom order", async () => {+ const trace = createTrace({+ project_id: projectId,+ });++ await createTracesCh([trace]);++ const traces = await caller.traces.all({+ projectId,+ filter: [+ {+ column: "timestamp",+ type: "datetime",+ operator: ">=",+ value: new Date(new Date().getTime() - 1000).toISOString(),+ },+ ],+ searchQuery: null,+ searchType: ["id"],+ page: 0,+ limit: 50,+ orderBy: {+ column: "latency",+ order: "DESC",+ },+ });++ expect(traces.traces.length).toBeGreaterThan(0);+ });++ it("list traces with user id search", async () => {+ const trace = createTrace({+ project_id: projectId,+ });++ await createTracesCh([trace]);++ const traces = await caller.traces.all({+ projectId,+ filter: [+ {+ column: "timestamp",+ type: "datetime",+ operator: ">=",+ value: new Date(new Date().getTime() - 1000).toISOString(),+ },+ ],+ searchQuery: "test",+ searchType: ["id", "content"],+ page: 0,+ limit: 50,+ orderBy: {+ column: "latency",+ order: "DESC",+ },+ });++ expect(traces.traces.length).toBeGreaterThan(0);+ });++ it("list traces with complex scores and observations filter", async () => {+ const trace = createTrace({+ project_id: projectId,+ });++ await createTracesCh([trace]);++ const traces = await caller.traces.all({+ projectId,+ filter: [+ {+ column: "timestamp",+ type: "datetime",+ operator: ">=",+ value: new Date(new Date().getTime() - 1000).toISOString(),+ },+ {+ column: "Input Cost ($)",+ operator: ">",+ type: "number",+ value: 0,+ },+ {+ column: "Input Tokens",+ operator: "=",+ type: "number",+ value: 0,+ },+ {+ column: "Total Tokens",+ operator: "=",+ type: "number",+ value: 0,+ },+ {+ column: "Scores (numeric)",+ key: "toxicity-v2",+ operator: "=",+ type: "numberObject",+ value: 0,+ },+ ],+ searchQuery: "test",+ searchType: ["id", "content"],+ page: 0,+ limit: 50,+ orderBy: {+ column: "latency",+ order: "DESC",+ },+ });++ expect(traces.traces.length).toBe(0);+ });+ });+describe("traces.byId", () => {it("access private trace", async () => {const trace = createTrace({diff --git a/web/src/__tests__/async/users-ui-table.servertest.ts b/web/src/__tests__/async/users-ui-table.servertest.tsindex bfc4d21664..6421795d67 100644--- a/web/src/__tests__/async/users-ui-table.servertest.ts+++ b/web/src/__tests__/async/users-ui-table.servertest.ts@@ -65,4 +65,69 @@ describe("getUserMetrics function", () => {totalCost: 125, // 50 + 75});});++ it("should return correct user metrics for a trace with two observations and timestamp filter", async () => {+ const userId = uuidv4();+ const traceId = uuidv4();++ const trace = createTrace({+ id: traceId,+ project_id: projectId,+ user_id: userId,+ });++ await createTracesCh([trace]);++ const observation1 = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ project_id: projectId,+ usage_details: {+ input: 100,+ output: 200,+ total: 300,+ },+ total_cost: 50,+ type: "GENERATION",+ });++ const observation2 = createObservationObject({+ id: uuidv4(),+ trace_id: traceId,+ project_id: projectId,+ usage_details: {+ input: 150,+ output: 250,+ total: 400,+ },+ total_cost: 75,+ type: "GENERATION",+ });++ await createObservationsInClickhouse([observation1, observation2]);++ const userMetrics = await getUserMetrics(+ projectId,+ [userId],+ [+ {+ column: "timestamp",+ type: "datetime",+ operator: ">=",+ value: new Date(new Date().getTime() - 1000),+ },+ ],+ );++ expect(userMetrics.length).toBe(1);+ expect(userMetrics[0]).toMatchObject({+ userId: userId,+ inputUsage: 250, // 100 + 150+ outputUsage: 450, // 200 + 250+ totalUsage: 700, // 300 + 400+ observationCount: 2,+ traceCount: 1,+ totalCost: 125, // 50 + 75+ });+ });});