🪢 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
chore: migrate traces table to AMTs (#7853)
Steffen Schmitzb3de5fd71a6e
diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.tsindex f7efaa7727..2fadf61518 100644--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts@@ -6,6 +6,7 @@ export const clickhouseSearchCondition = (query?: string,searchType?: TracingSearchType[],tablePrefix?: string,+ useTracesAmtCompatMode: boolean = false,) => {const prefix = tablePrefix ? `${tablePrefix}.` : "";@@ -13,9 +14,11 @@ export const clickhouseSearchCondition = (!searchType || searchType.includes("id")? `${prefix}id ILIKE {searchString: String} OR user_id ILIKE {searchString: String} OR ${prefix}name ILIKE {searchString: String}`: null,- searchType && searchType.includes("content")+ searchType && searchType.includes("content") && !useTracesAmtCompatMode? `${prefix}input ILIKE {searchString: String} OR ${prefix}output ILIKE {searchString: String}`- : null,+ : searchType && searchType.includes("content") && useTracesAmtCompatMode+ ? `finalizeAggregation(${prefix}input) ILIKE {searchString: String} OR finalizeAggregation(${prefix}output) ILIKE {searchString: String}`+ : null,].filter(Boolean);return {diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex 787c5a0cd0..f3350c7154 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -21,7 +21,9 @@ import {parseClickhouseUTCDateTimeFormat,queryClickhouse,reduceUsageOrCostDetails,+ getTimeframesTracesAMT,} from "../repositories";+import { measureAndReturn } from "../clickhouse/measureAndReturn";import { TracingSearchType } from "../../interfaces/search";import { ObservationLevelType, TraceDomain } from "../../domain";import { ClickHouseClientConfigOptions } from "@clickhouse/client";@@ -217,54 +219,6 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {clickhouseConfigs,} = props;- let sqlSelect: string;- switch (select) {- case "count":- sqlSelect = "count(*) as count";- break;- case "metrics":- 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`;- break;- case "rows":- sqlSelect = `- t.id as id,- t.project_id as project_id,- t.timestamp as timestamp,- t.tags as tags,- 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,- t.public as public`;- break;- case "identifiers":- sqlSelect = `- t.id as id,- t.project_id as projectId,- t.timestamp as timestamp`;- break;- default:- throw new Error(`Unknown select type: ${select}`);- }-const { tracesFilter, scoresFilter, observationsFilter } =getProjectIdDefaultFilter(projectId, { tracesPrefix: "t" });@@ -329,149 +283,318 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {const scoresFilterRes = scoresFilter.apply();const observationFilterRes = observationsFilter.apply();- const search = clickhouseSearchCondition(searchQuery, searchType, "t");-- const defaultOrder = orderBy?.order && orderBy?.column === "timestamp";- const orderByCols = [- ...tracesTableUiColumnDefinitions,- {- clickhouseSelect: "toDate(t.timestamp)",- uiTableName: "timestamp_to_date",- uiTableId: "timestamp_to_date",- clickhouseTableName: "traces",- },- {- clickhouseSelect: "t.event_ts",- uiTableName: "event_ts",- uiTableId: "event_ts",- clickhouseTableName: "traces",- },- ];- const chOrderBy = orderByToClickhouseSql(- [- defaultOrder- ? [- {- column: "timestamp_to_date",- order: orderBy.order,- },- { column: "timestamp", order: orderBy.order },- { column: "event_ts", order: "DESC" as "DESC" },- ]- : null,- orderBy ?? null,- ].flat(),- orderByCols,- );-- // complex query ahead:- // - we only join scores and observations if we really need them to speed up default views- // - we use FINAL on traces only in case we not need to order by something different than time. Otherwise we cannot guarantee correct reads.- // - we filter the observations and scores as much as possible before joining them to traces.- // - we order by todate(timestamp), event_ts desc per default and do not use FINAL.- // In this case, CH is able to read the data only from the latest date from disk and filtering them in memory. No need to read all data e.g. for 1 month from disk.-- const query = `+ const observationsAndScoresCTE = `WITH observations_stats AS (SELECTCOUNT(*) AS observation_count,- sumMap(usage_details) as usage_details,- SUM(total_cost) AS total_cost,- date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds,- countIf(level = 'ERROR') as error_count,- countIf(level = 'WARNING') as warning_count,- countIf(level = 'DEFAULT') as default_count,- countIf(level = 'DEBUG') as debug_count,- multiIf(- arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',- arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',- arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',- 'DEBUG'- ) AS aggregated_level,- sumMap(cost_details) as cost_details,- trace_id,- project_id- FROM observations o FINAL+ sumMap(usage_details) as usage_details,+ SUM(total_cost) AS total_cost,+ date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds,+ countIf(level = 'ERROR') as error_count,+ countIf(level = 'WARNING') as warning_count,+ countIf(level = 'DEFAULT') as default_count,+ countIf(level = 'DEBUG') as debug_count,+ multiIf(+ arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',+ arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',+ arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',+ 'DEBUG'+ ) AS aggregated_level,+ sumMap(cost_details) as cost_details,+ trace_id,+ project_id+ FROM observations o FINALWHERE o.project_id = {projectId: String}- ${timeStampFilter ? `AND o.start_time >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}- ${observationsFilter ? `AND ${observationFilterRes.query}` : ""}+ ${timeStampFilter ? `AND o.start_time >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}+ ${observationsFilter ? `AND ${observationFilterRes.query}` : ""}GROUP BY trace_id, project_id),- scores_avg AS (- SELECT- project_id,- trace_id,- -- For numeric scores, use tuples of (name, avg_value)- groupArrayIf(- tuple(name, avg_value),- data_type IN ('NUMERIC', 'BOOLEAN')- ) AS scores_avg,- -- For categorical scores, use name:value format for improved query performance- groupArrayIf(- concat(name, ':', string_value),- data_type = 'CATEGORICAL' AND notEmpty(string_value)- ) AS score_categories- FROM (- SELECT- project_id,- trace_id,- name,- data_type,- string_value,- avg(value) as avg_value- FROM scores s FINAL- WHERE- project_id = {projectId: String}- ${timeStampFilter ? `AND s.timestamp >= {traceTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}- ${scoresFilterRes ? `AND ${scoresFilterRes.query}` : ""}- GROUP BY- project_id,- trace_id,- name,- data_type,- string_value- ) tmp- GROUP BY project_id, trace_id- )- 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" || 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}- ${chOrderBy}- -- This is used for metrics and row queries. Count has only one result.- -- This is only used for default ordering. Otherwise, we use final.- ${["metrics", "rows", "identifiers"].includes(select) && defaultOrder ? "LIMIT 1 BY id, project_id" : ""}- ${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ scores_avg AS (+ SELECT+ project_id,+ trace_id,+ -- For numeric scores, use tuples of (name, avg_value)+ groupArrayIf(+ tuple(name, avg_value),+ data_type IN ('NUMERIC', 'BOOLEAN')+ ) AS scores_avg,+ -- For categorical scores, use name:value format for improved query performance+ groupArrayIf(+ concat(name, ':', string_value),+ data_type = 'CATEGORICAL' AND notEmpty(string_value)+ ) AS score_categories+ FROM (+ SELECT+ project_id,+ trace_id,+ name,+ data_type,+ string_value,+ avg(value) as avg_value+ FROM scores s FINAL+ WHERE+ project_id = {projectId: String}+ ${timeStampFilter ? `AND s.timestamp >= {traceTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}+ ${scoresFilterRes ? `AND ${scoresFilterRes.query}` : ""}+ GROUP BY+ project_id,+ trace_id,+ name,+ data_type,+ string_value+ ) tmp+ GROUP BY project_id, trace_id+ )`;- const res = await queryClickhouse<- SelectReturnTypeMap[keyof SelectReturnTypeMap]- >({- query: query,- params: {- limit: limit,- offset: limit && page ? limit * page : 0,- traceTimestamp: timeStampFilter?.value.getTime(),- projectId: projectId,- ...tracesFilterRes.params,- ...observationFilterRes.params,- ...scoresFilterRes.params,- ...search.params,+ return measureAndReturn({+ operationName: "getTracesTableGeneric",+ projectId: props.projectId,+ input: props,+ existingExecution: async (props) => {+ let sqlSelect: string;+ switch (select) {+ case "count":+ sqlSelect = "count(*) as count";+ break;+ case "metrics":+ 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`;+ break;+ case "rows":+ sqlSelect = `+ t.id as id,+ t.project_id as project_id,+ t.timestamp as timestamp,+ t.tags as tags,+ 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,+ t.public as public`;+ break;+ case "identifiers":+ sqlSelect = `+ t.id as id,+ t.project_id as projectId,+ t.timestamp as timestamp`;+ break;+ default:+ throw new Error(`Unknown select type: ${select}`);+ }++ const search = clickhouseSearchCondition(searchQuery, searchType, "t");++ const defaultOrder = orderBy?.order && orderBy?.column === "timestamp";+ const orderByCols = [+ ...tracesTableUiColumnDefinitions,+ {+ clickhouseSelect: "toDate(t.timestamp)",+ uiTableName: "timestamp_to_date",+ uiTableId: "timestamp_to_date",+ clickhouseTableName: "traces",+ },+ {+ clickhouseSelect: "t.event_ts",+ uiTableName: "event_ts",+ uiTableId: "event_ts",+ clickhouseTableName: "traces",+ },+ ];+ const chOrderBy = orderByToClickhouseSql(+ [+ defaultOrder+ ? [+ {+ column: "timestamp_to_date",+ order: orderBy.order,+ },+ { column: "timestamp", order: orderBy.order },+ { column: "event_ts", order: "DESC" as "DESC" },+ ]+ : null,+ orderBy ?? null,+ ].flat(),+ orderByCols,+ );++ // complex query ahead:+ // - we only join scores and observations if we really need them to speed up default views+ // - we use FINAL on traces only in case we not need to order by something different than time. Otherwise we cannot guarantee correct reads.+ // - we filter the observations and scores as much as possible before joining them to traces.+ // - we order by todate(timestamp), event_ts desc per default and do not use FINAL.+ // In this case, CH is able to read the data only from the latest date from disk and filtering them in memory. No need to read all data e.g. for 1 month from disk.++ const query = `+ ${observationsAndScoresCTE}++ 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" || 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}+ ${chOrderBy}+ -- This is used for metrics and row queries. Count has only one result.+ -- This is only used for default ordering. Otherwise, we use final.+ ${["metrics", "rows", "identifiers"].includes(select) && defaultOrder ? "LIMIT 1 BY id, project_id" : ""}+ ${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ `;++ const res = await queryClickhouse<+ SelectReturnTypeMap[keyof SelectReturnTypeMap]+ >({+ query: query,+ params: {+ limit: limit,+ offset: limit && page ? limit * page : 0,+ traceTimestamp: timeStampFilter?.value.getTime(),+ projectId: projectId,+ ...tracesFilterRes.params,+ ...observationFilterRes.params,+ ...scoresFilterRes.params,+ ...search.params,+ },+ tags: {+ ...(props.tags ?? {}),+ feature: "tracing",+ type: "traces-table",+ projectId,+ },+ clickhouseConfigs,+ });++ return res;},- tags: {- ...(props.tags ?? {}),- feature: "tracing",- type: "traces-table",- projectId,+ newExecution: async () => {+ let sqlSelect: string;+ switch (select) {+ case "count":+ sqlSelect = "count(*) as count";+ break;+ case "metrics":+ 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`;+ 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`;+ break;+ case "identifiers":+ sqlSelect = `+ t.id as id,+ t.project_id as projectId,+ t.timestamp as timestamp`;+ break;+ default:+ throw new Error(`Unknown select type: ${select}`);+ }++ const search = clickhouseSearchCondition(+ searchQuery,+ searchType,+ "t",+ true,+ );++ const defaultOrder = orderBy?.order && orderBy?.column === "timestamp";+ const chOrderBy = orderByToClickhouseSql(+ [+ defaultOrder ? [{ column: "timestamp", order: orderBy.order }] : null,+ orderBy ?? null,+ ].flat(),+ tracesTableUiColumnDefinitions,+ );++ const tracesAmt =+ select === "metrics"+ ? "traces_all_amt"+ : getTimeframesTracesAMT(timeStampFilter?.value);++ const query = `+ ${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` : ""}+ ${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}+ ${chOrderBy}+ ${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ `;++ const res = await queryClickhouse<+ SelectReturnTypeMap[keyof SelectReturnTypeMap]+ >({+ query: query,+ params: {+ limit: limit,+ offset: limit && page ? limit * page : 0,+ traceTimestamp: timeStampFilter?.value.getTime(),+ projectId: projectId,+ ...tracesFilterRes.params,+ ...observationFilterRes.params,+ ...scoresFilterRes.params,+ ...search.params,+ },+ tags: {+ ...(props.tags ?? {}),+ feature: "tracing",+ type: "traces-table",+ projectId,+ },+ clickhouseConfigs,+ });++ return res;},- clickhouseConfigs,});-- return res;}export const getTracesTableCount = async (props: {