Skip to content

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

fix: traces export performance (#9876)

Max Deichmann1c9a5e81c95e
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index e039cb6b70..c7bb1f1e12 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -77,21 +77,98 @@ describe("batch export test suite", () => {
name: observations[0].name,
type: observations[0].type,
test: [score.value],
+ input: "Hello World",
+ output: "Hello John",
+ metadata: expect.objectContaining({
+ source: "API",
+ server: "Node",
+ }),
}),
expect.objectContaining({
id: observations[1].id,
name: observations[1].name,
type: observations[1].type,
+ input: "Hello World",
+ output: "Hello John",
}),
expect.objectContaining({
id: observations[2].id,
name: observations[2].name,
type: observations[2].type,
+ input: "Hello World",
+ output: "Hello John",
}),
]),
);
});
+ it("should export filtered observations", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const observations = [
+ createObservation({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "test1",
+ start_time: new Date("2024-01-01").getTime(),
+ }),
+ createObservation({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "EVENT",
+ name: "test2",
+ start_time: new Date("2024-01-02").getTime(),
+ }),
+ createObservation({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "SPAN",
+ name: "test3",
+ start_time: new Date("2024-01-03").getTime(),
+ }),
+ ];
+
+ await createObservationsCh(observations);
+
+ const stream = await getObservationStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "name",
+ value: ["test1", "test2"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+
+ const exportedNames = rows.map((row) => row.name);
+ expect(exportedNames).toEqual(expect.arrayContaining(["test1", "test2"]));
+ expect(exportedNames).toHaveLength(2);
+
+ // Verify input/output/metadata are properly exported
+ rows.forEach((row) => {
+ expect(row.input).toBe("Hello World");
+ expect(row.output).toBe("Hello John");
+ expect(row.metadata).toEqual(
+ expect.objectContaining({
+ source: "API",
+ server: "Node",
+ }),
+ );
+ });
+ });
+
it("should export observations with filter", async () => {
const { projectId } = await createOrgProjectAndApiKey();
@@ -145,6 +222,16 @@ describe("batch export test suite", () => {
const exportedNames = rows.map((row) => row.name);
expect(exportedNames).toEqual(expect.arrayContaining(["test1", "test2"]));
expect(exportedNames).toHaveLength(2);
+
+ // Verify input/output/metadata are present
+ rows.forEach((row) => {
+ expect(row.input).toBe("Hello World");
+ expect(row.output).toBe("Hello John");
+ expect(row.metadata).toMatchObject({
+ source: "API",
+ server: "Node",
+ });
+ });
});
it("should export sessions", async () => {
@@ -376,7 +463,15 @@ describe("batch export test suite", () => {
data_type: "CATEGORICAL",
});
- await createScoresCh([score, qualitativeScore]);
+ const booleanScore = createTraceScore({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ name: "is_correct",
+ value: 1,
+ data_type: "BOOLEAN",
+ });
+
+ await createScoresCh([score, qualitativeScore, booleanScore]);
const stream = await getTraceStream({
projectId: projectId,
@@ -398,15 +493,18 @@ describe("batch export test suite", () => {
id: traces[0].id,
test: [score.value],
qualitative_test: ["This is some qualitative text"],
+ is_correct: [1],
}),
expect.objectContaining({
id: traces[1].id,
test: null,
qualitative_test: null,
+ is_correct: null,
}),
]),
);
});
+
it("should export traces with filter and sort", async () => {
const { projectId } = await createOrgProjectAndApiKey();
diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
index 4adf704ebb..3e7ee45b48 100644
--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts
+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
@@ -54,7 +54,7 @@ const isGenerationTimestampFilter = (
): filter is TimeFilter => {
return filter.column === "Start Time" && filter.type === "datetime";
};
-const isTraceTimestampFilter = (
+export const isTraceTimestampFilter = (
filter: FilterCondition,
): filter is TimeFilter => {
return filter.column === "Timestamp" && filter.type === "datetime";
@@ -593,7 +593,9 @@ export function prepareScoresForOutput(
// If this score name already exists in acc, use its existing type
const existingValues = acc[score.name];
const newValue =
- score.dataType === "NUMERIC" ? score.value : score.stringValue;
+ score.dataType === "NUMERIC" || score.dataType === "BOOLEAN"
+ ? score.value
+ : score.stringValue;
if (!isPresent(newValue)) return acc;
if (!existingValues) {
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index e60122cf1d..7e7f3e2b7f 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -211,10 +211,10 @@ export const getObservationStream = async (props: {
o.prompt_version as "prompt_version",
internal_model_id as "internal_model_id",
if(isNull(end_time), NULL, date_diff('millisecond', start_time, end_time)) as latency,
- if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time)) as "time_to_first_token",
- o.input,
- o.output,
- o.metadata,
+ if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time)) as "time_to_first_token",
+ o.input as input,
+ o.output as output,
+ o.metadata as metadata,
t.name as traceName,
t.tags as traceTags,
t.timestamp as traceTimestamp,
@@ -240,6 +240,7 @@ export const getObservationStream = async (props: {
stringValue: string;
}[]
| undefined;
+ score_categories: string[] | undefined;
} & {
traceName: string;
traceTags: string[];
@@ -280,6 +281,30 @@ export const getObservationStream = async (props: {
const model = await modelCache.getModel(row.internal_model_id);
const modelData = enrichObservationWithModelData(model);
+ // Process numeric/boolean scores (tuples from ClickHouse)
+ 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(":"),
+ };
+ },
+ );
+
+ const outputScores: Record<string, string[] | number[]> =
+ prepareScoresForOutput([...numericScores, ...categoricalScores]);
+
yield getChunkWithFlattenedScores(
[
{
@@ -292,14 +317,7 @@ export const getObservationStream = async (props: {
traceTimestamp: row.traceTimestamp,
userId: row.userId,
...modelData,
- scores: prepareScoresForOutput(
- (row.scores_avg ?? []).map((score: any) => ({
- name: score[0],
- value: score[1],
- dataType: score[2],
- stringValue: score[3],
- })),
- ),
+ scores: outputScores,
},
],
distinctScoreNames.reduce(
diff --git a/worker/src/features/database-read-stream/trace-stream.ts b/worker/src/features/database-read-stream/trace-stream.ts
index 75405a61ba..364fb58634 100644
--- a/worker/src/features/database-read-stream/trace-stream.ts
+++ b/worker/src/features/database-read-stream/trace-stream.ts
@@ -1,6 +1,5 @@
import {
FilterCondition,
- TimeFilter,
TracingSearchType,
ScoreDataType,
} from "@langfuse/shared";
@@ -13,20 +12,16 @@ import {
tracesTableUiColumnDefinitions,
clickhouseSearchCondition,
parseClickhouseUTCDateTimeFormat,
+ StringFilter,
} from "@langfuse/shared/src/server";
import { Readable } from "stream";
import { env } from "../../env";
import {
getChunkWithFlattenedScores,
+ isTraceTimestampFilter,
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;
@@ -83,34 +78,21 @@ export const getTraceStream = async (props: {
const appliedTracesFilter = tracesFilter.apply();
+ const scoresFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "scores",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ }),
+ ]);
+
+ const appliedScoresFilter = scoresFilter.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 (
+ WITH scores_agg AS (
SELECT
project_id,
trace_id,
@@ -133,8 +115,7 @@ export const getTraceStream = async (props: {
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)
+ WHERE ${appliedScoresFilter.query}
GROUP BY
project_id,
trace_id,
@@ -145,26 +126,32 @@ export const getTraceStream = async (props: {
) 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`;
+ SELECT
+ t.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,
+ s.scores_avg as scores_avg,
+ s.score_categories as score_categories
+ FROM traces t
+ LEFT JOIN scores_agg s ON s.trace_id = t.id AND s.project_id = t.project_id
+ WHERE t.project_id = {projectId: String}
+ ${appliedTracesFilter.query ? `AND ${appliedTracesFilter.query}` : ""}
+ ${search.query}
+ LIMIT 1 BY id, project_id
+ LIMIT {rowLimit: Int64}
+ `;
const asyncGenerator = queryClickhouseStream<{
id: string;
@@ -197,6 +184,7 @@ export const getTraceStream = async (props: {
projectId,
rowLimit,
...appliedTracesFilter.params,
+ ...appliedScoresFilter.params,
...search.params,
},
clickhouseConfigs,
@@ -220,7 +208,7 @@ export const getTraceStream = async (props: {
`Streaming traces for project ${projectId}: processed ${recordsProcessed} rows`,
);
- // Process numeric/boolean scores
+ // Process numeric/boolean scores (tuples from ClickHouse)
const numericScores = (row.scores_avg ?? []).map((score: any) => ({
name: score[0],
value: score[1],
@@ -236,7 +224,7 @@ export const getTraceStream = async (props: {
name,
value: null,
dataType: "CATEGORICAL" as ScoreDataType,
- stringValue: valueParts.join(":"), // rejoin in case value contains ':'
+ stringValue: valueParts.join(":"),
};
},
);