🪢 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: only read trace identifiers for historic eval read stream (#7080)
Max Deichmann6147e9c51825
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex 535a42f83f..c448395971 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -157,7 +157,7 @@ export type TracesTableMetricsClickhouseReturnType = {};export type FetchTracesTableProps = {- select: "count" | "rows" | "metrics";+ select: "count" | "rows" | "metrics" | "identifiers";projectId: string;filter: FilterState;searchQuery?: string;@@ -169,84 +169,42 @@ export type FetchTracesTableProps = {tags?: Record<string, string>;};-export const getTracesTableCount = async (props: {- projectId: string;- filter: FilterState;- searchQuery?: string;- searchType: TracingSearchType[];- orderBy?: OrderByState;- limit?: number;- page?: number;-}) => {- const countRows = await getTracesTableGeneric<{ count: string }>({- select: "count",- tags: { kind: "count" },- ...props,- });-- const converted = countRows.map((row) => ({- count: Number(row.count),- }));-- return converted.length > 0 ? converted[0].count : 0;+// Define return type mapping for better type safety+type SelectReturnTypeMap = {+ count: { count: string };+ metrics: TracesTableMetricsClickhouseReturnType;+ rows: TracesTableReturnType;+ identifiers: { id: string; projectId: string; timestamp: string };};-export const getTracesTableMetrics = async (props: {- projectId: string;- filter: FilterState;- searchQuery?: string;- orderBy?: OrderByState;- limit?: number;- page?: number;- clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;-}): Promise<Array<Omit<TracesMetricsUiReturnType, "scores">>> => {- const countRows =- await getTracesTableGeneric<TracesTableMetricsClickhouseReturnType>({- select: "metrics",- tags: { kind: "analytic" },- ...props,- });+// Function overloads for type-safe select-specific returns+async function getTracesTableGeneric(+ // eslint-disable-next-line no-unused-vars+ props: FetchTracesTableProps & { select: "count" },+): Promise<Array<SelectReturnTypeMap["count"]>>;- return countRows.map(convertToUITableMetrics);-};+async function getTracesTableGeneric(+ // eslint-disable-next-line no-unused-vars+ props: FetchTracesTableProps & { select: "metrics" },+): Promise<Array<SelectReturnTypeMap["metrics"]>>;-export const getTracesTable = async (p: {- projectId: string;- filter: FilterState;- searchQuery?: string;- searchType?: TracingSearchType[];- orderBy?: OrderByState;- limit?: number;- page?: number;- clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;-}) => {- const {- projectId,- filter,- searchQuery,- searchType,- orderBy,- limit,- page,- clickhouseConfigs,- } = p;- const rows = await getTracesTableGeneric<TracesTableReturnType>({- select: "rows",- tags: { kind: "list" },- projectId,- filter,- searchQuery,- searchType,- orderBy,- limit,- page,- clickhouseConfigs,- });+async function getTracesTableGeneric(+ // eslint-disable-next-line no-unused-vars+ props: FetchTracesTableProps & { select: "rows" },+): Promise<Array<SelectReturnTypeMap["rows"]>>;- return rows.map(convertToUiTableRows);-};+async function getTracesTableGeneric(+ // eslint-disable-next-line no-unused-vars+ props: FetchTracesTableProps & { select: "identifiers" },+): Promise<Array<SelectReturnTypeMap["identifiers"]>>;++// Implementation with union type for internal use+async function getTracesTableGeneric(+ // eslint-disable-next-line no-unused-vars+ props: FetchTracesTableProps,+): Promise<Array<SelectReturnTypeMap[keyof SelectReturnTypeMap]>>;-const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {+async function getTracesTableGeneric(props: FetchTracesTableProps) {const {select,projectId,@@ -297,6 +255,12 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {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}`);}@@ -484,7 +448,9 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;- const res = await queryClickhouse<T>({+ const res = await queryClickhouse<+ SelectReturnTypeMap[keyof SelectReturnTypeMap]+ >({query: query,params: {limit: limit,@@ -506,4 +472,103 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {});return res;+}++export const getTracesTableCount = async (props: {+ projectId: string;+ filter: FilterState;+ searchQuery?: string;+ searchType: TracingSearchType[];+ orderBy?: OrderByState;+ limit?: number;+ page?: number;+}) => {+ const countRows = await getTracesTableGeneric({+ select: "count",+ tags: { kind: "count" },+ ...props,+ });++ const converted = countRows.map((row) => ({+ count: Number(row.count),+ }));++ return converted.length > 0 ? converted[0].count : 0;+};++export const getTracesTableMetrics = async (props: {+ projectId: string;+ filter: FilterState;+ searchQuery?: string;+ orderBy?: OrderByState;+ limit?: number;+ page?: number;+ clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;+}): Promise<Array<Omit<TracesMetricsUiReturnType, "scores">>> => {+ const countRows = await getTracesTableGeneric({+ select: "metrics",+ tags: { kind: "analytic" },+ ...props,+ });++ return countRows.map(convertToUITableMetrics);+};++export const getTracesTable = async (p: {+ projectId: string;+ filter: FilterState;+ searchQuery?: string;+ searchType?: TracingSearchType[];+ orderBy?: OrderByState;+ limit?: number;+ page?: number;+ clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;+}) => {+ const {+ projectId,+ filter,+ searchQuery,+ searchType,+ orderBy,+ limit,+ page,+ clickhouseConfigs,+ } = p;+ const rows = await getTracesTableGeneric({+ select: "rows",+ tags: { kind: "list" },+ projectId,+ filter,+ searchQuery,+ searchType,+ orderBy,+ limit,+ page,+ clickhouseConfigs,+ });++ return rows.map(convertToUiTableRows);+};++export const getTraceIdentifiers = async (props: {+ projectId: string;+ filter: FilterState;+ searchQuery?: string;+ searchType?: TracingSearchType[];+ orderBy?: OrderByState;+ limit?: number;+ page?: number;+ clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;+}) => {+ const identifiers = await getTracesTableGeneric({+ select: "identifiers",+ tags: { kind: "list" },+ ...props,+ });++ return identifiers.map((row) => ({+ id: row.id,+ projectId: row.projectId,+ timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),+ }));};diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex bcf937f37a..20643f6231 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -12,7 +12,10 @@ import {BatchExportTableName,FilterCondition,} from "@langfuse/shared";-import { getDatabaseReadStream } from "../database-read-stream/getDatabaseReadStream";+import {+ getDatabaseReadStream,+ getTraceIdentifierStream,+} from "../database-read-stream/getDatabaseReadStream";import { processClickhouseTraceDelete } from "../traces/processClickhouseTraceDelete";import { env } from "../../env";import { Job } from "bullmq";@@ -185,17 +188,22 @@ export const handleBatchActionJob = async (return;}- const dbReadStream = await getDatabaseReadStream({- projectId: projectId,- cutoffCreatedAt: new Date(cutoffCreatedAt),- filter: convertDatesInFiltersFromStrings(query.filter ?? []),- orderBy: query.orderBy,- tableName:- targetObject === "trace"- ? BatchExportTableName.Traces- : BatchExportTableName.DatasetRunItems,- exportLimit: env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,- });+ const dbReadStream =+ targetObject === "trace"+ ? await getTraceIdentifierStream({+ projectId: projectId,+ cutoffCreatedAt: new Date(cutoffCreatedAt),+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ orderBy: query.orderBy,+ }) // when reading from clickhouse, we only want to read the necessary identifiers.+ : await getDatabaseReadStream({+ projectId: projectId,+ cutoffCreatedAt: new Date(cutoffCreatedAt),+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ orderBy: query.orderBy,+ tableName: BatchExportTableName.DatasetRunItems,+ exportLimit: env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,+ });const evalCreatorQueue = CreateEvalQueue.getInstance();if (!evalCreatorQueue) {diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.tsindex 720dc6bb25..d933f21c6b 100644--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts@@ -5,6 +5,7 @@ import {BatchExportQueryType,ScoreDomain,evalDatasetFormFilterCols,+ OrderByState,} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import {@@ -21,6 +22,7 @@ import {getTracesByIds,getScoresForTraces,tableColumnsToSqlFilterAndPrefix,+ getTraceIdentifiers,} from "@langfuse/shared/src/server";import Decimal from "decimal.js";import { env } from "../../env";@@ -459,3 +461,48 @@ export function prepareScoresForOutput({} as Record<string, string[] | number[]>,);}++export type TraceIdentifiers = {+ id: string;+ projectId: string;+ timestamp: Date;+};++export const getTraceIdentifierStream = async (props: {+ projectId: string;+ cutoffCreatedAt: Date;+ filter: FilterCondition[];+ orderBy: OrderByState;+ exportLimit?: number;+}): Promise<DatabaseReadStream<Array<TraceIdentifiers>>> => {+ const { projectId, cutoffCreatedAt, filter, orderBy, exportLimit } = props;++ const createdAtCutoffFilter: FilterCondition = {+ column: "timestamp",+ operator: "<",+ value: cutoffCreatedAt,+ type: "datetime",+ };++ const clickhouseConfigs = {+ request_timeout: 120_000,+ };++ return new DatabaseReadStream<TraceIdentifiers>(+ async (pageSize: number, offset: number) => {+ return await getTraceIdentifiers({+ projectId,+ filter: filter+ ? [...filter, createdAtCutoffFilter]+ : [createdAtCutoffFilter],+ searchType: ["id" as const],+ orderBy,+ limit: pageSize,+ page: Math.floor(offset / pageSize),+ clickhouseConfigs,+ });+ },+ env.BATCH_EXPORT_PAGE_SIZE,+ exportLimit,+ );+};