Skip to content

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

feat(export): add comments to trace, observation, and session exports (#9898)

Michael Fröhlich39d426ee0645
diff --git a/packages/shared/src/server/utils/transforms/stringify.ts b/packages/shared/src/server/utils/transforms/stringify.ts
index 70d3b88167..3704b74ff4 100644
--- a/packages/shared/src/server/utils/transforms/stringify.ts
+++ b/packages/shared/src/server/utils/transforms/stringify.ts
@@ -1,5 +1,12 @@
-export const stringify = (data: any): string => {
- return JSON.stringify(data, (key, value) =>
- typeof value === "bigint" ? Number.parseInt(value.toString()) : value,
+export const stringify = (data: any, key?: string): string => {
+ // For comment fields, use pretty-print formatting for better readability
+ // Other fields use compact format to reduce file size
+ const indent = key === "comments" ? 2 : undefined;
+
+ return JSON.stringify(
+ data,
+ (k, value) =>
+ typeof value === "bigint" ? Number.parseInt(value.toString()) : value,
+ indent,
);
};
diff --git a/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts b/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts
index 429189d4d7..68ac0831bb 100644
--- a/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts
+++ b/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts
@@ -24,7 +24,7 @@ export function transformStreamToCsv(): Transform {
// Convert the object to a CSV line and push it
const csvRow = headers.map((header) => {
const field = row[header] ?? "";
- let str = stringify(field);
+ let str = stringify(field, header);
// escape and format fields that contain commas
if (str.includes(",")) {
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index 87b6057df8..abf42cb310 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -13,11 +13,13 @@ import { usdFormatter } from "@/src/utils/numbers";
import { getNumberFromMap } from "@/src/utils/map-utils";
import Link from "next/link";
import { useRouter } from "next/router";
-import { useEffect, useState } from "react";
+import { useEffect, useState, useCallback } from "react";
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import { Button } from "@/src/components/ui/button";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { useSession } from "next-auth/react";
+import { Download } from "lucide-react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import Page from "@/src/components/layouts/page";
import {
Popover,
@@ -147,6 +149,8 @@ export const SessionPage: React.FC<{
const router = useRouter();
const { setDetailPageList } = useDetailPageLists();
const userSession = useSession();
+ const capture = usePostHogClientCapture();
+ const utils = api.useUtils();
const [visibleTraces, setVisibleTraces] = useState(PAGE_SIZE);
const session = api.sessions.byIdWithScores.useQuery(
{
@@ -165,6 +169,53 @@ export const SessionPage: React.FC<{
},
);
+ const sessionComments = api.comments.getByObjectId.useQuery({
+ projectId,
+ objectId: sessionId,
+ objectType: "SESSION",
+ });
+
+ const downloadSessionAsJson = useCallback(async () => {
+ // Fetch fresh session and trace comments data
+ const [sessionCommentsData, traceCommentsData] = await Promise.all([
+ sessionComments.refetch(),
+ utils.comments.getTraceCommentsBySessionId.fetch({
+ projectId,
+ sessionId,
+ }),
+ ]);
+
+ // Add comments to each trace
+ const sessionWithTraceComments = session.data
+ ? {
+ ...session.data,
+ traces: session.data.traces.map((trace) => ({
+ ...trace,
+ comments: traceCommentsData[trace.id] ?? [],
+ })),
+ }
+ : session.data;
+
+ const exportData = {
+ ...sessionWithTraceComments,
+ comments: sessionCommentsData.data ?? [],
+ };
+
+ const jsonString = JSON.stringify(exportData, null, 2);
+ const blob = new Blob([jsonString], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `session-${sessionId}.json`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+
+ capture("session_detail:download_button_click");
+ }, [session.data, sessionId, projectId, capture, sessionComments, utils]);
+
const { openPeek, closePeek, resolveDetailNavigationPath, expandPeek } =
usePeekNavigation({
expandConfig: {
@@ -264,6 +315,14 @@ export const SessionPage: React.FC<{
listKey="sessions"
/>
)}
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={downloadSessionAsJson}
+ title="Download session as JSON"
+ >
+ <Download className="h-4 w-4" />
+ </Button>
<CommentDrawerButton
key="comment"
variant="outline"
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 1c53e7c8fc..75ade8ef94 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -53,6 +53,7 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"
import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
+import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
export type SessionTableRow = {
id: string;
@@ -710,6 +711,15 @@ export default function SessionsTable({
tableName={BatchExportTableName.Sessions}
/>
) : null,
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState: backendFilterState,
+ orderByState,
+ }}
+ tableName={BatchExportTableName.Sessions}
+ key="batchExport"
+ />,
]}
columns={columns}
columnVisibility={columnVisibility}
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 3495f2f78b..872cd8a510 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -34,10 +34,7 @@ import { Button } from "@/src/components/ui/button";
import { cn } from "@/src/utils/tailwind";
import useSessionStorage from "@/src/components/useSessionStorage";
import { JsonExpansionProvider } from "@/src/components/trace/JsonExpansionContext";
-import {
- buildTraceUiData,
- downloadTraceAsJson as downloadTraceUtil,
-} from "@/src/components/trace/lib/helpers";
+import { buildTraceUiData } from "@/src/components/trace/lib/helpers";
import {
ResizablePanelGroup,
ResizablePanel,
@@ -197,11 +194,6 @@ export function Trace(props: {
objectType: "OBSERVATION",
},
{
- trpc: {
- context: {
- skipBatch: true,
- },
- },
refetchOnMount: false, // prevents refetching loops
enabled: isAuthenticatedAndProjectMember,
},
@@ -214,11 +206,6 @@ export function Trace(props: {
objectType: "TRACE",
},
{
- trpc: {
- context: {
- skipBatch: true,
- },
- },
refetchOnMount: false, // prevents refetching loops
enabled: isAuthenticatedAndProjectMember,
},
@@ -289,13 +276,36 @@ export function Trace(props: {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- const handleDownloadTrace = useCallback(() => {
- downloadTraceUtil({
+ const traceComments = api.comments.getByObjectId.useQuery({
+ projectId: props.projectId,
+ objectId: props.trace.id,
+ objectType: "TRACE",
+ });
+
+ const downloadTraceAsJson = useCallback(async () => {
+ // Fetch fresh comments data
+ const comments = await traceComments.refetch();
+
+ const exportData = {
trace: props.trace,
observations: props.observations,
- });
+ comments: comments.data ?? [],
+ };
+
+ const jsonString = JSON.stringify(exportData, null, 2);
+ const blob = new Blob([jsonString], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `trace-${props.trace.id}.json`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+
capture("trace_detail:download_button_click");
- }, [props.trace, props.observations, capture]);
+ }, [props.trace, props.observations, capture, traceComments]);
const [expandedItems, setExpandedItems] = useSessionStorage<string[]>(
`${props.trace.id}-expanded`,
@@ -537,7 +547,7 @@ export function Trace(props: {
<Button
variant="ghost"
size="icon"
- onClick={handleDownloadTrace}
+ onClick={downloadTraceAsJson}
title="Download trace as JSON"
className="h-7 w-7"
>
@@ -791,7 +801,7 @@ export function Trace(props: {
<Button
variant="ghost"
size="icon"
- onClick={handleDownloadTrace}
+ onClick={downloadTraceAsJson}
title="Download trace as JSON"
className="h-7 w-7"
>
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index b7cbc45378..f7f2af3e26 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -80,7 +80,7 @@ const events = {
"duplicate_button_click",
"duplicate_form_submit",
],
- session_detail: ["publish_button_click"],
+ session_detail: ["publish_button_click", "download_button_click"],
eval_config: [
"new_form_submit",
"new_form_open",
diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.ts
index 5417eeadb0..aca3c44440 100644
--- a/web/src/server/api/routers/comments.ts
+++ b/web/src/server/api/routers/comments.ts
@@ -195,6 +195,7 @@ export const commentsRouter = createTRPCRouter({
scope: "comments:read",
});
+ // For single object view, we want DESC order (most recent first)
const comments = await ctx.prisma.$queryRaw<
Array<{
id: string;
@@ -214,13 +215,13 @@ export const commentsRouter = createTRPCRouter({
u.image AS "authorUserImage",
u.name AS "authorUserName"
FROM comments c
- LEFT JOIN users u ON u.id = c.author_user_id AND u.id in (SELECT user_id FROM organization_memberships WHERE org_id = ${ctx.session.orgId})
+ LEFT JOIN users u ON u.id = c.author_user_id
WHERE
c."project_id" = ${input.projectId}
AND c."object_id" = ${input.objectId}
AND c."object_type"::text = ${input.objectType}
ORDER BY
- c.created_at ASC
+ c.created_at DESC
`,
);
@@ -337,6 +338,12 @@ export const commentsRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:read",
+ });
+
const clickhouseTraces = await getTracesIdentifierForSession(
input.projectId,
input.sessionId,
@@ -359,4 +366,72 @@ export const commentsRouter = createTRPCRouter({
.map(({ objectId, count }) => [objectId, Number(count)]),
);
}),
+ getTraceCommentsBySessionId: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ sessionId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:read",
+ });
+
+ const clickhouseTraces = await getTracesIdentifierForSession(
+ input.projectId,
+ input.sessionId,
+ );
+
+ const traceIds = clickhouseTraces.map((t) => t.id);
+
+ if (traceIds.length === 0) {
+ return {};
+ }
+
+ // Fetch all comments for the traces with user information (ASC order for chronological listing)
+ const enrichedComments = await ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ objectId: string;
+ content: string;
+ createdAt: Date;
+ authorUserId: string | null;
+ authorUserImage: string | null;
+ authorUserName: string | null;
+ }>
+ >(
+ Prisma.sql`
+ SELECT
+ c.id,
+ c.object_id AS "objectId",
+ c.content,
+ c.created_at AS "createdAt",
+ u.id AS "authorUserId",
+ u.image AS "authorUserImage",
+ u.name AS "authorUserName"
+ FROM comments c
+ LEFT JOIN users u ON u.id = c.author_user_id
+ WHERE
+ c."project_id" = ${input.projectId}
+ AND c."object_type"::text = 'TRACE'
+ AND c."object_id" = ANY(${traceIds}::text[])
+ ORDER BY
+ c.created_at ASC
+ `,
+ );
+
+ // Group comments by trace ID
+ const commentsByTrace: Record<string, typeof enrichedComments> = {};
+ for (const comment of enrichedComments) {
+ if (!commentsByTrace[comment.objectId]) {
+ commentsByTrace[comment.objectId] = [];
+ }
+ commentsByTrace[comment.objectId].push(comment);
+ }
+
+ return commentsByTrace;
+ }),
});
diff --git a/web/src/utils/map-utils.ts b/web/src/utils/map-utils.ts
index bb3738911c..a939a7a4f3 100644
--- a/web/src/utils/map-utils.ts
+++ b/web/src/utils/map-utils.ts
@@ -1,23 +1,33 @@
/**
- * Safely gets a number value from a Map, returning undefined if the key doesn't exist.
- * Specifically typed for Maps that return numbers.
+ * Safely gets a number value from a Map or Record object, returning undefined if the key doesn't exist.
+ * Supports both Map and plain object (Record) types for backward compatibility.
*/
export function getNumberFromMap(
- map: Map<any, any> | undefined,
+ mapOrRecord: Map<any, any> | Record<string, number> | undefined,
key: any,
): number | undefined {
- return map?.get(key) as number | undefined;
+ if (!mapOrRecord) return undefined;
+ if (mapOrRecord instanceof Map) {
+ return mapOrRecord.get(key) as number | undefined;
+ }
+ return mapOrRecord[key];
}
/**
- * Type-casts a Map with unknown generic types to a Map<string, number>.
- * Useful to handle Maps returned from tRPC queries where TypeScript
+ * Type-casts a Map or Record with unknown generic types to the appropriate number type.
+ * Useful to handle Maps/Records returned from tRPC queries where TypeScript
* can't properly infer the generic types.
*/
export function castToNumberMap(
- map: Map<unknown, unknown> | undefined,
+ mapOrRecord: Map<unknown, unknown> | Record<string, unknown> | undefined,
): Map<string, number> | undefined {
- return map as Map<string, number> | undefined;
+ if (!mapOrRecord) return undefined;
+ if (mapOrRecord instanceof Map) {
+ return mapOrRecord as Map<string, number>;
+ }
+ return new Map(
+ Object.entries(mapOrRecord).map(([key, value]) => [key, Number(value)]),
+ );
}
/**
diff --git a/worker/src/features/database-read-stream/fetchCommentsForExport.ts b/worker/src/features/database-read-stream/fetchCommentsForExport.ts
new file mode 100644
index 0000000000..a16a936105
--- /dev/null
+++ b/worker/src/features/database-read-stream/fetchCommentsForExport.ts
@@ -0,0 +1,72 @@
+import { prisma } from "@langfuse/shared/src/db";
+import { type CommentObjectType } from "@prisma/client";
+
+export type ExportComment = {
+ id: string;
+ content: string;
+ author_email: string | null;
+ created_at: string; // ISO format
+};
+
+/**
+ * Fetches comments for a batch of objects during export operations.
+ * Groups comments by objectId for efficient lookup.
+ *
+ * @param projectId - The project ID to filter comments
+ * @param objectType - Type of object (TRACE, OBSERVATION, SESSION, etc.)
+ * @param objectIds - Array of object IDs to fetch comments for
+ * @returns Map of objectId to array of comments (chronological order)
+ */
+export async function fetchCommentsForExport(
+ projectId: string,
+ objectType: CommentObjectType,
+ objectIds: string[],
+): Promise<Map<string, ExportComment[]>> {
+ if (objectIds.length === 0) {
+ return new Map();
+ }
+
+ // Note: We need to queryRaw because authorUserId has no foreignKey constraint set
+ const comments = await prisma.$queryRaw<
+ Array<{
+ id: string;
+ object_id: string;
+ content: string;
+ author_user_id: string | null;
+ author_email: string | null;
+ created_at: Date;
+ }>
+ >`
+ SELECT
+ c.id,
+ c.object_id,
+ c.content,
+ c.author_user_id,
+ u.email as author_email,
+ c.created_at
+ FROM comments c
+ LEFT JOIN users u ON c.author_user_id = u.id
+ WHERE c.project_id = ${projectId}
+ AND c.object_type = ${objectType}::"CommentObjectType"
+ AND c.object_id = ANY(${objectIds}::text[])
+ ORDER BY c.created_at ASC
+ `;
+
+ // Group by objectId
+ const commentsByObject = new Map<string, ExportComment[]>();
+
+ for (const comment of comments) {
+ if (!commentsByObject.has(comment.object_id)) {
+ commentsByObject.set(comment.object_id, []);
+ }
+
+ commentsByObject.get(comment.object_id)!.push({
+ id: comment.id,
+ content: comment.content,
+ author_email: comment.author_email,
+ created_at: comment.created_at.toISOString(),
+ });
+ }
+
+ return commentsByObject;
+}
diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
index d6e618f4d2..72f6b64c0b 100644
--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts
+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
@@ -21,15 +21,16 @@ import {
getScoresForObservations,
getTracesTable,
getTracesTableMetrics,
- getTracesByIds,
- getScoresForTraces,
tableColumnsToSqlFilterAndPrefix,
getTraceIdentifiers,
getDatasetRunItemsCh,
+ getTracesByIds,
+ getScoresForTraces,
} from "@langfuse/shared/src/server";
import Decimal from "decimal.js";
import { env } from "../../env";
import { BatchExportTracesRow, BatchExportSessionsRow } from "./types";
+import { fetchCommentsForExport } from "./fetchCommentsForExport";
const tableNameToTimeFilterColumn: Record<BatchTableNames, string> = {
scores: "timestamp",
@@ -216,7 +217,7 @@ export const getDatabaseReadStreamPaginated = async ({
public: true,
},
});
- return sessions.map((s) => {
+ const rows = sessions.map((s) => {
const row: BatchExportSessionsRow = {
id: s.session_id,
userIds: s.user_ids,
@@ -238,6 +239,19 @@ export const getDatabaseReadStreamPaginated = async ({
};
return row;
});
+
+ // Fetch comments for all sessions in this page
+ const sessionComments = await fetchCommentsForExport(
+ projectId,
+ "SESSION",
+ sessions.map((s) => s.session_id),
+ );
+
+ // Add comments to each session
+ return rows.map((row) => ({
+ ...row,
+ comments: sessionComments.get(row.id) ?? [],
+ }));
},
env.BATCH_EXPORT_PAGE_SIZE,
rowLimit,
@@ -295,7 +309,23 @@ export const getDatabaseReadStreamPaginated = async ({
};
});
- return getChunkWithFlattenedScores(chunk, emptyScoreColumns);
+ // Fetch comments for all observations in this page
+ const observationComments = await fetchCommentsForExport(
+ projectId,
+ "OBSERVATION",
+ generations.map((g) => g.id),
+ );
+
+ // Add comments to flattened chunk
+ const flattenedChunk = getChunkWithFlattenedScores(
+ chunk,
+ emptyScoreColumns,
+ );
+
+ return flattenedChunk.map((obs: any) => ({
+ ...obs,
+ comments: observationComments.get(obs.id) ?? [],
+ }));
},
env.BATCH_EXPORT_PAGE_SIZE,
rowLimit,
@@ -404,7 +434,23 @@ export const getDatabaseReadStreamPaginated = async ({
};
});
- return getChunkWithFlattenedScores(chunk, emptyScoreColumns);
+ // Fetch comments for all traces in this page
+ const traceComments = await fetchCommentsForExport(
+ projectId,
+ "TRACE",
+ traces.map((t) => t.id),
+ );
+
+ // Add comments to each trace
+ const chunkWithComments = chunk.map((trace) => ({
+ ...trace,
+ comments: traceComments.get(trace.id) ?? [],
+ }));
+
+ return getChunkWithFlattenedScores(
+ chunkWithComments,
+ emptyScoreColumns,
+ );
},
env.BATCH_EXPORT_PAGE_SIZE,
rowLimit,
@@ -486,7 +532,7 @@ export const getDatabaseReadStreamPaginated = async ({
updated_at: Date;
}>
>`
- SELECT
+ SELECT
di.id,
di.project_id,
di.dataset_id,
@@ -499,7 +545,7 @@ export const getDatabaseReadStreamPaginated = async ({
di.source_observation_id,
di.created_at,
di.updated_at
- FROM dataset_items di
+ FROM dataset_items di
JOIN datasets d ON di.dataset_id = d.id AND di.project_id = d.project_id
WHERE di.project_id = ${projectId}
AND di.created_at < ${cutoffCreatedAt}
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index 600558538b..a69e510bc2 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -24,8 +24,11 @@ import {
getChunkWithFlattenedScores,
prepareScoresForOutput,
} from "./getDatabaseReadStream";
+import { fetchCommentsForExport } from "./fetchCommentsForExport";
import type { Model, Price } from "@prisma/client";
+const BATCH_SIZE = 1000; // Fetch comments in batches for efficiency
+
type ModelWithPrice = Model & { Price: Price[] };
/**
@@ -275,67 +278,135 @@ export const getObservationStream = async (props: {
},
});
+ // Helper function to process a single observation row
+ const modelCache = createModelCache(projectId);
+ const emptyScoreColumns = distinctScoreNames.reduce(
+ (acc, name) => ({ ...acc, [name]: null }),
+ {} as Record<string, null>,
+ );
+
+ type ObservationRow = ObservationRecordReadType & {
+ scores_avg:
+ | {
+ name: string;
+ value: number;
+ dataType: ScoreDataType;
+ stringValue: string;
+ }[]
+ | undefined;
+ score_categories: string[] | undefined;
+ } & {
+ traceName: string;
+ traceTags: string[];
+ traceTimestamp: Date;
+ userId: string | null;
+ };
+
+ const processObservationRow = async (
+ bufferedRow: ObservationRow,
+ commentsByObservation: Map<string, any[]>,
+ ) => {
+ // Fetch model data from cache (or database if not cached)
+ const model = await modelCache.getModel(bufferedRow.internal_model_id);
+ const modelData = enrichObservationWithModelData(model);
+
+ // Process numeric/boolean scores (tuples from ClickHouse)
+ const numericScores = (bufferedRow.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 = (bufferedRow.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]);
+
+ // Get comments for this observation
+ const observationComments = commentsByObservation.get(bufferedRow.id) ?? [];
+
+ return getChunkWithFlattenedScores(
+ [
+ {
+ ...convertObservation(bufferedRow, {
+ truncated: false,
+ shouldJsonParse: true,
+ }),
+ traceName: bufferedRow.traceName,
+ traceTags: bufferedRow.traceTags,
+ traceTimestamp: bufferedRow.traceTimestamp,
+ userId: bufferedRow.userId,
+ ...modelData,
+ scores: outputScores,
+ comments: observationComments,
+ },
+ ],
+ emptyScoreColumns,
+ )[0];
+ };
+
// Convert async generator to Node.js Readable stream
+ // eslint-disable-next-line no-unused-vars
let recordsProcessed = 0;
- const modelCache = createModelCache(projectId);
return Readable.from(
(async function* () {
+ let rowBuffer: ObservationRow[] = [];
+ let observationIds: string[] = [];
+
for await (const row of asyncGenerator) {
- recordsProcessed++;
- if (recordsProcessed % 10000 === 0)
- logger.info(
- `Streaming observations for project ${projectId}: processed ${recordsProcessed} rows`,
+ rowBuffer.push(row);
+ observationIds.push(row.id);
+
+ // Process in batches
+ if (rowBuffer.length >= BATCH_SIZE) {
+ // Fetch comments for this batch
+ const commentsByObservation = await fetchCommentsForExport(
+ projectId,
+ "OBSERVATION",
+ observationIds,
);
- // Fetch model data from cache (or database if not cached)
- 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(":"),
- };
- },
+ // Process each row in the buffer
+ for (const bufferedRow of rowBuffer) {
+ recordsProcessed++;
+
+ yield await processObservationRow(
+ bufferedRow,
+ commentsByObservation,
+ );
+ }
+
+ // Reset buffers
+ rowBuffer = [];
+ observationIds = [];
+ }
+ }
+
+ // Process remaining rows in buffer
+ if (rowBuffer.length > 0) {
+ const commentsByObservation = await fetchCommentsForExport(
+ projectId,
+ "OBSERVATION",
+ observationIds,
);
- const outputScores: Record<string, string[] | number[]> =
- prepareScoresForOutput([...numericScores, ...categoricalScores]);
-
- yield getChunkWithFlattenedScores(
- [
- {
- ...convertObservation(row, {
- truncated: false,
- shouldJsonParse: true,
- }),
- traceName: row.traceName,
- traceTags: row.traceTags,
- traceTimestamp: row.traceTimestamp,
- userId: row.userId,
- ...modelData,
- scores: outputScores,
- },
- ],
- distinctScoreNames.reduce(
- (acc, name) => ({ ...acc, [name]: null }),
- {} as Record<string, null>,
- ),
- )[0];
+ for (const bufferedRow of rowBuffer) {
+ recordsProcessed++;
+ yield await processObservationRow(bufferedRow, commentsByObservation);
+ }
}
})(),
);
diff --git a/worker/src/features/database-read-stream/trace-stream.ts b/worker/src/features/database-read-stream/trace-stream.ts
index 651182bbf8..a59e887420 100644
--- a/worker/src/features/database-read-stream/trace-stream.ts
+++ b/worker/src/features/database-read-stream/trace-stream.ts
@@ -21,6 +21,9 @@ import {
isTraceTimestampFilter,
prepareScoresForOutput,
} from "./getDatabaseReadStream";
+import { fetchCommentsForExport } from "./fetchCommentsForExport";
+
+const BATCH_SIZE = 1000; // Fetch comments in batches for efficiency
export const getTraceStream = async (props: {
projectId: string;
@@ -206,67 +209,123 @@ export const getTraceStream = async (props: {
},
});
+ // Helper function to process a single trace row
+ const processTraceRow = (
+ bufferedRow: Awaited<ReturnType<typeof asyncGenerator.next>>["value"],
+ commentsByTrace: Map<string, any[]>,
+ ) => {
+ // Process numeric/boolean scores (tuples from ClickHouse)
+ const numericScores = (bufferedRow.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 = (bufferedRow.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]);
+
+ // Get comments for this trace
+ const traceComments = commentsByTrace.get(bufferedRow.id) ?? [];
+
+ return getChunkWithFlattenedScores(
+ [
+ {
+ id: bufferedRow.id,
+ timestamp:
+ bufferedRow.timestamp instanceof Date
+ ? bufferedRow.timestamp
+ : parseClickhouseUTCDateTimeFormat(bufferedRow.timestamp),
+ name: bufferedRow.name ?? "",
+ userId: bufferedRow.user_id,
+ sessionId: bufferedRow.session_id,
+ release: bufferedRow.release,
+ version: bufferedRow.version,
+ environment: bufferedRow.environment ?? undefined,
+ tags: bufferedRow.tags,
+ bookmarked: bufferedRow.bookmarked,
+ public: bufferedRow.public,
+ input: bufferedRow.input,
+ output: bufferedRow.output,
+ metadata: bufferedRow.metadata,
+ scores: outputScores,
+ comments: traceComments,
+ },
+ ],
+ emptyScoreColumns,
+ )[0];
+ };
+
// Convert async generator to Node.js Readable stream
let recordsProcessed = 0;
return Readable.from(
(async function* () {
+ let rowBuffer: Awaited<
+ ReturnType<typeof asyncGenerator.next>
+ >["value"][] = [];
+ let traceIds: string[] = [];
+
for await (const row of asyncGenerator) {
- recordsProcessed++;
- if (recordsProcessed % 10000 === 0)
- logger.info(
- `Streaming traces for project ${projectId}: processed ${recordsProcessed} rows`,
+ rowBuffer.push(row);
+ traceIds.push(row.id);
+
+ // Process in batches
+ if (rowBuffer.length >= BATCH_SIZE) {
+ // Fetch comments for this batch
+ const commentsByTrace = await fetchCommentsForExport(
+ projectId,
+ "TRACE",
+ traceIds,
);
- // 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 each row in the buffer
+ for (const bufferedRow of rowBuffer) {
+ recordsProcessed++;
+ if (recordsProcessed % 10000 === 0)
+ logger.info(
+ `Streaming traces for project ${projectId}: processed ${recordsProcessed} rows`,
+ );
+
+ yield processTraceRow(bufferedRow, commentsByTrace);
+ }
+
+ // Reset buffers
+ rowBuffer = [];
+ traceIds = [];
+ }
+ }
- // 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(":"),
- };
- },
+ // Process remaining rows in buffer
+ if (rowBuffer.length > 0) {
+ const commentsByTrace = await fetchCommentsForExport(
+ projectId,
+ "TRACE",
+ traceIds,
);
- const outputScores: Record<string, string[] | number[]> =
- prepareScoresForOutput([...numericScores, ...categoricalScores]);
+ for (const bufferedRow of rowBuffer) {
+ recordsProcessed++;
+ if (recordsProcessed % 10000 === 0)
+ logger.info(
+ `Streaming traces for project ${projectId}: processed ${recordsProcessed} rows`,
+ );
- 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];
+ yield processTraceRow(bufferedRow, commentsByTrace);
+ }
}
})(),
);