Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore: stream trace csv export from clickhouse (#9845)

Max Deichmann905ebf8b7e8f
diff --git a/packages/shared/scripts/seeder/seed-clickhouse.ts b/packages/shared/scripts/seeder/seed-clickhouse.ts
index 5d5833dd78..1fe22a285e 100644
--- a/packages/shared/scripts/seeder/seed-clickhouse.ts
+++ b/packages/shared/scripts/seeder/seed-clickhouse.ts
@@ -14,7 +14,7 @@ async function main() {
}
await prepareClickhouse(projectIds, {
numberOfDays: 3,
- totalObservations: 10000,
+ totalObservations: 100000,
numberOfRuns: 3,
});
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index 63b57a293a..e039cb6b70 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -13,6 +13,7 @@ import { BatchExportTableName, DatasetStatus } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { getDatabaseReadStreamPaginated } from "../features/database-read-stream/getDatabaseReadStream";
import { getObservationStream } from "../features/database-read-stream/observation-stream";
+import { getTraceStream } from "../features/database-read-stream/trace-stream";
describe("batch export test suite", () => {
it("should export observations", async () => {
@@ -359,34 +360,9 @@ describe("batch export test suite", () => {
await createTracesCh(traces);
- const generations = [
- createObservation({
- project_id: projectId,
- trace_id: traces[0].id,
- type: "GENERATION",
- start_time: new Date().getTime() - 1000,
- end_time: new Date().getTime(),
- }),
- createObservation({
- project_id: projectId,
- trace_id: traces[1].id,
- type: "GENERATION",
- start_time: new Date().getTime() - 2000,
- end_time: new Date().getTime(),
- }),
- createObservation({
- project_id: projectId,
- trace_id: traces[1].id,
- type: "GENERATION",
- start_time: new Date().getTime() - 2123,
- end_time: new Date().getTime(),
- }),
- ];
-
const score = createTraceScore({
project_id: projectId,
trace_id: traces[0].id,
- observation_id: generations[0].id,
name: "test",
value: 123,
});
@@ -394,7 +370,6 @@ describe("batch export test suite", () => {
const qualitativeScore = createTraceScore({
project_id: projectId,
trace_id: traces[0].id,
- observation_id: generations[0].id,
name: "qualitative_test",
value: undefined,
string_value: "This is some qualitative text",
@@ -402,14 +377,11 @@ describe("batch export test suite", () => {
});
await createScoresCh([score, qualitativeScore]);
- await createObservationsCh(generations);
- const stream = await getDatabaseReadStreamPaginated({
+ const stream = await getTraceStream({
projectId: projectId,
- tableName: BatchExportTableName.Traces,
cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
filter: [],
- orderBy: { column: "timestamp", order: "DESC" },
});
const rows: any[] = [];
@@ -424,13 +396,11 @@ describe("batch export test suite", () => {
expect.arrayContaining([
expect.objectContaining({
id: traces[0].id,
- latency: expect.closeTo(1.0, 0.1), // allows deviation of ±0.1
test: [score.value],
qualitative_test: ["This is some qualitative text"],
}),
expect.objectContaining({
id: traces[1].id,
- latency: expect.closeTo(2.123, 0.1), // allows deviation of ±0.1
test: null,
qualitative_test: null,
}),
@@ -473,9 +443,8 @@ describe("batch export test suite", () => {
await createTracesCh(traces);
- const stream = await getDatabaseReadStreamPaginated({
+ const stream = await getTraceStream({
projectId: projectId,
- tableName: BatchExportTableName.Traces,
cutoffCreatedAt: new Date("2024-01-02"),
filter: [
{
@@ -491,7 +460,6 @@ describe("batch export test suite", () => {
value: true,
},
],
- orderBy: { column: "timestamp", order: "ASC" },
});
const rows: any[] = [];
@@ -1314,12 +1282,10 @@ describe("batch export test suite", () => {
await createTracesCh(traces);
- const streamByName = await getDatabaseReadStreamPaginated({
+ const streamByName = await getTraceStream({
projectId: projectId,
- tableName: BatchExportTableName.Traces,
cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
filter: [],
- orderBy: { column: "timestamp", order: "ASC" },
searchQuery: "findable-trace",
searchType: ["id"],
});
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index eded5047fc..551ef0e9ab 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -19,6 +19,7 @@ import {
import { env } from "../../env";
import { getDatabaseReadStreamPaginated } from "../database-read-stream/getDatabaseReadStream";
import { getObservationStream } from "../database-read-stream/observation-stream";
+import { getTraceStream } from "../database-read-stream/trace-stream";
export const handleBatchExportJob = async (
batchExportJob: BatchExportJobType,
@@ -96,11 +97,17 @@ export const handleBatchExportJob = async (
cutoffCreatedAt: jobDetails.createdAt,
...parsedQuery.data,
})
- : await getDatabaseReadStreamPaginated({
- projectId,
- cutoffCreatedAt: jobDetails.createdAt,
- ...parsedQuery.data,
- });
+ : parsedQuery.data.tableName === BatchExportTableName.Traces
+ ? await getTraceStream({
+ projectId,
+ cutoffCreatedAt: jobDetails.createdAt,
+ ...parsedQuery.data,
+ })
+ : await getDatabaseReadStreamPaginated({
+ projectId,
+ cutoffCreatedAt: jobDetails.createdAt,
+ ...parsedQuery.data,
+ });
// Transform data to desired format
let rowCount = 0;
diff --git a/worker/src/features/database-read-stream/trace-stream.ts b/worker/src/features/database-read-stream/trace-stream.ts
new file mode 100644
index 0000000000..75405a61ba
--- /dev/null
+++ b/worker/src/features/database-read-stream/trace-stream.ts
@@ -0,0 +1,275 @@
+import {
+ FilterCondition,
+ TimeFilter,
+ TracingSearchType,
+ ScoreDataType,
+} from "@langfuse/shared";
+import {
+ getDistinctScoreNames,
+ queryClickhouseStream,
+ logger,
+ FilterList,
+ createFilterFromFilterState,
+ tracesTableUiColumnDefinitions,
+ clickhouseSearchCondition,
+ parseClickhouseUTCDateTimeFormat,
+} from "@langfuse/shared/src/server";
+import { Readable } from "stream";
+import { env } from "../../env";
+import {
+ getChunkWithFlattenedScores,
+ prepareScoresForOutput,
+} from "./getDatabaseReadStream";
+
+const isTraceTimestampFilter = (
+ filter: FilterCondition,
+): filter is TimeFilter => {
+ return filter.column === "timestamp" && filter.type === "datetime";
+};
+
+export const getTraceStream = async (props: {
+ projectId: string;
+ cutoffCreatedAt: Date;
+ filter: FilterCondition[] | null;
+ searchQuery?: string;
+ searchType?: TracingSearchType[];
+ rowLimit?: number;
+}): Promise<Readable> => {
+ const {
+ projectId,
+ cutoffCreatedAt,
+ filter = [],
+ searchQuery,
+ searchType,
+ rowLimit = env.BATCH_EXPORT_ROW_LIMIT,
+ } = props;
+
+ const clickhouseConfigs = {
+ request_timeout: 120_000,
+ join_algorithm: "partial_merge",
+ };
+
+ // Get distinct score names for empty columns
+ const distinctScoreNames = await getDistinctScoreNames({
+ projectId,
+ cutoffCreatedAt,
+ filter: filter ?? [],
+ isTimestampFilter: isTraceTimestampFilter,
+ clickhouseConfigs,
+ });
+
+ const emptyScoreColumns = distinctScoreNames.reduce(
+ (acc, name) => ({ ...acc, [name]: null }),
+ {} as Record<string, null>,
+ );
+
+ // Build filters for traces
+ const tracesFilter = new FilterList([]);
+
+ tracesFilter.push(
+ ...createFilterFromFilterState(
+ [
+ ...(filter ?? []),
+ {
+ column: "timestamp",
+ operator: "<" as const,
+ value: cutoffCreatedAt,
+ type: "datetime" as const,
+ },
+ ],
+ tracesTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedTracesFilter = tracesFilter.apply();
+
+ const search = clickhouseSearchCondition(searchQuery, searchType, "t");
+
+ const query = `
+ WITH traces_cte AS (
+ SELECT
+ t.id as trace_id,
+ t.project_id as project_id,
+ t.timestamp as timestamp,
+ t.name as name,
+ t.user_id as user_id,
+ t.session_id as session_id,
+ t.release as release,
+ t.version as version,
+ t.environment as environment,
+ t.tags as tags,
+ t.bookmarked as bookmarked,
+ t.public as public,
+ t.input as input,
+ t.output as output,
+ t.metadata as metadata
+ FROM traces t
+ WHERE t.project_id = {projectId: String}
+ ${appliedTracesFilter.query ? `AND ${appliedTracesFilter.query}` : ""}
+ ${search.query}
+ LIMIT 1 BY id, project_id
+ LIMIT {rowLimit: Int64}
+ ),
+ scores_agg AS (
+ SELECT
+ project_id,
+ trace_id,
+ -- For numeric scores, use tuples of (name, avg_value, data_type, string_value)
+ groupArrayIf(
+ tuple(name, avg_value, data_type, string_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 FINAL
+ WHERE project_id = {projectId: String}
+ AND trace_id IN (SELECT trace_id FROM traces_cte)
+ GROUP BY
+ project_id,
+ trace_id,
+ name,
+ data_type,
+ string_value,
+ execution_trace_id
+ ) tmp
+ GROUP BY project_id, trace_id
+ )
+ SELECT
+ t.trace_id as id,
+ t.project_id as project_id,
+ t.timestamp as timestamp,
+ t.name as name,
+ t.user_id as user_id,
+ t.session_id as session_id,
+ t.release as release,
+ t.version as version,
+ t.environment as environment,
+ t.tags as tags,
+ t.bookmarked as bookmarked,
+ t.public as public,
+ t.input as input,
+ t.output as output,
+ t.metadata as metadata,
+ sa.scores_avg as scores_avg,
+ sa.score_categories as score_categories
+ FROM traces_cte t
+ LEFT JOIN scores_agg sa ON sa.trace_id = t.trace_id AND sa.project_id = t.project_id`;
+
+ const asyncGenerator = queryClickhouseStream<{
+ id: string;
+ project_id: string;
+ timestamp: Date;
+ name: string | null;
+ user_id: string | null;
+ session_id: string | null;
+ release: string | null;
+ version: string | null;
+ environment: string | null;
+ tags: string[];
+ bookmarked: boolean;
+ public: boolean;
+ input: unknown;
+ output: unknown;
+ metadata: unknown;
+ scores_avg:
+ | {
+ name: string;
+ avg_value: number;
+ data_type: ScoreDataType;
+ string_value: string;
+ }[]
+ | undefined;
+ score_categories: string[] | undefined;
+ }>({
+ query,
+ params: {
+ projectId,
+ rowLimit,
+ ...appliedTracesFilter.params,
+ ...search.params,
+ },
+ clickhouseConfigs,
+ tags: {
+ feature: "batch-export",
+ type: "trace",
+ kind: "export",
+ projectId,
+ },
+ });
+
+ // Convert async generator to Node.js Readable stream
+ let recordsProcessed = 0;
+
+ return Readable.from(
+ (async function* () {
+ for await (const row of asyncGenerator) {
+ recordsProcessed++;
+ if (recordsProcessed % 10000 === 0)
+ logger.info(
+ `Streaming traces for project ${projectId}: processed ${recordsProcessed} rows`,
+ );
+
+ // Process numeric/boolean scores
+ const numericScores = (row.scores_avg ?? []).map((score: any) => ({
+ name: score[0],
+ value: score[1],
+ dataType: score[2],
+ stringValue: score[3],
+ }));
+
+ // Process categorical scores (format: "name:value")
+ const categoricalScores = (row.score_categories ?? []).map(
+ (cat: string) => {
+ const [name, ...valueParts] = cat.split(":");
+ return {
+ name,
+ value: null,
+ dataType: "CATEGORICAL" as ScoreDataType,
+ stringValue: valueParts.join(":"), // rejoin in case value contains ':'
+ };
+ },
+ );
+
+ const outputScores: Record<string, string[] | number[]> =
+ prepareScoresForOutput([...numericScores, ...categoricalScores]);
+
+ yield getChunkWithFlattenedScores(
+ [
+ {
+ id: row.id,
+ timestamp:
+ row.timestamp instanceof Date
+ ? row.timestamp
+ : parseClickhouseUTCDateTimeFormat(row.timestamp),
+ name: row.name ?? "",
+ userId: row.user_id,
+ sessionId: row.session_id,
+ release: row.release,
+ version: row.version,
+ environment: row.environment ?? undefined,
+ tags: row.tags,
+ bookmarked: row.bookmarked,
+ public: row.public,
+ input: row.input,
+ output: row.output,
+ metadata: row.metadata,
+ scores: outputScores,
+ },
+ ],
+ emptyScoreColumns,
+ )[0];
+ }
+ })(),
+ );
+};
diff --git a/worker/src/features/database-read-stream/types.ts b/worker/src/features/database-read-stream/types.ts
index 13a7518700..ec2199c663 100644
--- a/worker/src/features/database-read-stream/types.ts
+++ b/worker/src/features/database-read-stream/types.ts
@@ -1,4 +1,3 @@
-import { ObservationLevelType } from "@langfuse/shared";
import Decimal from "decimal.js";
export type BatchExportSessionsRow = {
@@ -25,10 +24,7 @@ export type BatchExportTracesRow = {
timestamp: Date;
name: string;
userId?: string | null;
- level?: ObservationLevelType | null;
- observationCount?: number | null;
scores?: Record<string, string[] | number[]> | null;
- latency?: number | null;
release?: string | null;
version?: string | null;
sessionId?: string | null;
@@ -36,12 +32,4 @@ export type BatchExportTracesRow = {
output?: unknown | null;
metadata?: unknown | null;
tags: string[];
- usage: {
- promptTokens?: bigint | null;
- completionTokens?: bigint | null;
- totalTokens?: bigint | null;
- };
- inputCost?: Decimal | null;
- outputCost?: Decimal | null;
- totalCost?: Decimal | null;
};