Skip to content

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

fix(batch-export): read scores trace metadata from events table for v4 users (#14203)

Niklas Semmler97c153326abb
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 2b7a4ca367..aaa8d0d6b0 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -1,5 +1,6 @@
import { prisma } from "../../db";
import { Readable } from "stream";
+import type { ClickHouseClientConfigOptions } from "@clickhouse/client";
import type {
EventsObservation,
MetadataDomain,
@@ -3647,6 +3648,7 @@ export const hasAnySessionFromEventsTable = async (
export const getTraceMetadataByIdsFromEvents = async (props: {
projectId: string;
traceIds: string[];
+ clickhouseConfigs?: ClickHouseClientConfigOptions;
}) => {
if (props.traceIds.length === 0) return [];
@@ -3678,6 +3680,7 @@ export const getTraceMetadataByIdsFromEvents = async (props: {
query,
params: input.params,
tags: input.tags,
+ clickhouseConfigs: props.clickhouseConfigs,
preferredClickhouseService: "EventsReadOnly",
}),
});
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 495bfd9dbb..0f5059496d 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -1171,6 +1171,7 @@ const getScoresUiGeneric = async <T>(props: {
${excludeMetadata ? "" : "s.metadata,"}
s.trace_id,
s.session_id,
+ s.dataset_run_id,
s.observation_id,
s.author_user_id,
t.user_id,
@@ -1398,6 +1399,7 @@ const getScoresUiGenericFromEvents = async <T>(props: {
${excludeMetadata ? "" : "s.metadata,"}
s.trace_id,
s.session_id,
+ s.dataset_run_id,
s.observation_id,
s.author_user_id,
s.created_at,
@@ -1486,8 +1488,11 @@ export async function getScoresUiTableFromEvents(props: {
limit?: number;
offset?: number;
clickhouseConfigs?: ClickHouseClientConfigOptions;
+ // Defaults to true: the scores UI table only needs the hasMetadata flag.
+ // Batch exports pass false to include the full metadata payload.
+ excludeMetadata?: boolean;
}) {
- const { clickhouseConfigs, ...rest } = props;
+ const { clickhouseConfigs, excludeMetadata = true, ...rest } = props;
const rows = await getScoresUiGenericFromEvents<{
id: string;
@@ -1503,6 +1508,7 @@ export async function getScoresUiTableFromEvents(props: {
trace_id: string | null;
session_id: string | null;
dataset_run_id: string | null;
+ metadata?: Record<string, string>;
observation_id: string | null;
author_user_id: string | null;
config_id: string | null;
@@ -1516,7 +1522,7 @@ export async function getScoresUiTableFromEvents(props: {
}>({
select: "rows",
tags: { kind: "analytic" },
- excludeMetadata: true,
+ excludeMetadata,
includeHasMetadataFlag: true,
clickhouseConfigs,
...rest,
@@ -1526,10 +1532,10 @@ export async function getScoresUiTableFromEvents(props: {
const score = convertClickhouseScoreToDomain(
{
...row,
- metadata: {},
+ metadata: excludeMetadata ? {} : (row.metadata ?? {}),
long_string_value: "",
},
- false,
+ !excludeMetadata,
);
return {
...score,
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index 5b8c4b47be..cacc12443b 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -5,6 +5,7 @@ import {
createObservationsCh,
createOrgProjectAndApiKey,
createTraceScore,
+ createDatasetRunScore,
createScoresCh,
createTrace,
createTracesCh,
@@ -2358,6 +2359,75 @@ describe("batch export test suite", () => {
// ==================== EVENTS TABLE EXPORT TESTS ====================
maybeDescribe("events table export tests", () => {
+ it("should export scores with trace metadata from the events table when useEventsTable is true", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const score = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ name: "accuracy",
+ value: 0.95,
+ data_type: "NUMERIC",
+ metadata: { reason: "test-metadata" },
+ });
+ const runScore = createDatasetRunScore({
+ project_id: projectId,
+ name: "run-accuracy",
+ value: 0.5,
+ data_type: "NUMERIC",
+ });
+ await createScoresCh([score, runScore]);
+
+ // The trace exists only in the events table (v4 world) — no row is
+ // written to the legacy traces table, so the legacy traces JOIN would
+ // return empty trace metadata.
+ await createEventsCh([
+ createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ is_app_root: true,
+ trace_name: "events-trace",
+ user_id: "events-user",
+ tags: ["events-tag"],
+ }),
+ ]);
+
+ const stream = await getDatabaseReadStreamPaginated({
+ projectId,
+ tableName: BatchExportTableName.Scores,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ orderBy: { column: "timestamp", order: "DESC" },
+ useEventsTable: true,
+ });
+
+ const rows: any[] = [];
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+ const traceScoreRow = rows.find((r) => r.id === score.id);
+ expect(traceScoreRow).toMatchObject({
+ traceId,
+ name: "accuracy",
+ value: 0.95,
+ traceName: "events-trace",
+ userId: "events-user",
+ traceTags: ["events-tag"],
+ metadata: { reason: "test-metadata" },
+ });
+ // Dataset run scores have no trace; the export must keep the run id.
+ const runScoreRow = rows.find((r) => r.id === runScore.id);
+ expect(runScoreRow).toMatchObject({
+ traceId: null,
+ datasetRunId: runScore.dataset_run_id,
+ name: "run-accuracy",
+ value: 0.5,
+ });
+ });
+
it("should export sessions from the events table when useEventsTable is true", 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 2c7e1b85a1..a80a6dde11 100644
--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts
+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
@@ -13,6 +13,8 @@ import {
FullObservationsWithScores,
DatabaseReadStream,
getScoresUiTable,
+ getScoresUiTableFromEvents,
+ getTraceMetadataByIdsFromEvents,
getPublicSessionsFilter,
getSessionsWithMetrics,
getSessionsWithMetricsFromEvents,
@@ -97,6 +99,49 @@ export const getChunkWithFlattenedScores = <
});
};
+// Events-backed replacement for the legacy getScoresUiTable traces JOIN:
+// loads score rows without trace enrichment, then fills traceName /
+// traceUserId / traceTags from the events table for the page's trace ids.
+const getScoresWithTraceMetadataFromEvents = async (props: {
+ projectId: string;
+ filter: FilterCondition[];
+ orderBy: OrderByState;
+ limit: number;
+ offset: number;
+ clickhouseConfigs: Parameters<
+ typeof getScoresUiTableFromEvents
+ >[0]["clickhouseConfigs"];
+}) => {
+ const scores = await getScoresUiTableFromEvents({
+ ...props,
+ excludeMetadata: false,
+ });
+
+ const traceMetadata = await getTraceMetadataByIdsFromEvents({
+ projectId: props.projectId,
+ traceIds: [
+ ...new Set(
+ scores
+ .map((score) => score.traceId)
+ .filter((traceId): traceId is string => Boolean(traceId)),
+ ),
+ ],
+ clickhouseConfigs: props.clickhouseConfigs,
+ });
+
+ return scores.map((score) => {
+ const trace = traceMetadata.find((t) => t.id === score.traceId);
+ // `?? null` (not `|| null`): preserve explicit empty strings/arrays so
+ // rows serialize the same as the legacy traces-JOIN export path.
+ return {
+ ...score,
+ traceName: trace?.name ?? null,
+ traceUserId: trace?.user_id ?? null,
+ traceTags: trace?.tags ?? null,
+ };
+ });
+};
+
export const getDatabaseReadStreamPaginated = async ({
projectId,
tableName,
@@ -143,16 +188,31 @@ export const getDatabaseReadStreamPaginated = async ({
case "scores": {
return new DatabaseReadStream<unknown>(
async (pageSize: number, offset: number) => {
- const scores = await getScoresUiTable({
- projectId,
- filter: filter
- ? [...filter, createdAtCutoffFilter]
- : [createdAtCutoffFilter],
- orderBy,
- limit: pageSize,
- offset,
- clickhouseConfigs,
- });
+ const scoresFilter = filter
+ ? [...filter, createdAtCutoffFilter]
+ : [createdAtCutoffFilter];
+
+ // v4-enabled users (snapshotted as useEventsTable at dispatch) read
+ // scores without the legacy traces JOIN; trace metadata (name,
+ // userId, tags) is loaded from the events table instead, mirroring
+ // the scores UI (scores.allFromEvents + scores.metricsFromEvents).
+ const scores = useEventsTable
+ ? await getScoresWithTraceMetadataFromEvents({
+ projectId,
+ filter: scoresFilter,
+ orderBy,
+ limit: pageSize,
+ offset,
+ clickhouseConfigs,
+ })
+ : await getScoresUiTable({
+ projectId,
+ filter: scoresFilter,
+ orderBy,
+ limit: pageSize,
+ offset,
+ clickhouseConfigs,
+ });
// Get author user info for scores
// Only users that have valid project write access may write scores