Skip to content

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

feat(traces): Add new trace download endpoint (#13033)

Ben Bachem19ccc4768c8d
diff --git a/packages/shared/src/domain/observations.ts b/packages/shared/src/domain/observations.ts
index 9bcdf98c84..58a88dd5d4 100644
--- a/packages/shared/src/domain/observations.ts
+++ b/packages/shared/src/domain/observations.ts
@@ -79,6 +79,7 @@ export const ObservationSchema = z.object({
promptVersion: z.number().nullable(),
latency: z.number().nullable(),
timeToFirstToken: z.number().nullable(),
+ providedUsageDetails: z.record(z.string(), z.number()),
usageDetails: z.record(z.string(), z.number()),
costDetails: z.record(z.string(), z.number()),
providedCostDetails: z.record(z.string(), z.number()),
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 8430ad1263..1583d1edb2 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -100,6 +100,7 @@ export * from "./queries";
export * from "./queries/clickhouse-sql/orderby-factory";
export * from "./queries/clickhouse-sql/query-options";
export * from "./repositories";
+export * from "./repositories/observations";
export * from "./repositories/traces";
export * from "./repositories/dataset-items";
export * from "./utils/metadata_conversion";
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index ee79fec7e7..3e05c92570 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -102,6 +102,7 @@ const EVENTS_FIELDS = {
toolCallNames: 'e.tool_call_names as "tool_call_names"',
// Pricing tier
+ usagePricingTierId: 'e.usage_pricing_tier_id as "usage_pricing_tier_id"',
usagePricingTierName:
'e.usage_pricing_tier_name as "usage_pricing_tier_name"',
@@ -174,6 +175,8 @@ const FIELD_SETS = {
"updatedAt",
"providedModelName",
"totalCost",
+ "usagePricingTierId",
+ "usagePricingTierName",
"promptId",
"promptName",
"promptVersion",
@@ -212,6 +215,8 @@ const FIELD_SETS = {
"updatedAt",
"providedModelName",
"totalCost",
+ "usagePricingTierId",
+ "usagePricingTierName",
"promptId",
"promptName",
"promptVersion",
@@ -221,6 +226,8 @@ const FIELD_SETS = {
"traceName",
"release",
"tags",
+ // Keep lightweight tool names available even when heavy tool payloads are omitted.
+ "toolCallNames",
],
calculated: ["latency", "timeToFirstToken"],
io: ["input", "output"],
@@ -265,6 +272,8 @@ const FIELD_SETS = {
"providedCostDetails",
"costDetails",
"totalCost",
+ "usagePricingTierId",
+ "usagePricingTierName",
"completionStartTime",
],
byIdPrompt: ["promptId", "promptName", "promptVersion"],
@@ -293,7 +302,13 @@ const FIELD_SETS = {
],
time: ["completionStartTime", "createdAt", "updatedAt"],
model: ["providedModelName", "internalModelId", "modelParameters"],
- usage: ["usageDetails", "costDetails", "totalCost", "usagePricingTierName"],
+ usage: [
+ "usageDetails",
+ "costDetails",
+ "totalCost",
+ "usagePricingTierId",
+ "usagePricingTierName",
+ ],
prompt: ["promptId", "promptName", "promptVersion"],
metrics: ["latency", "timeToFirstToken"],
@@ -335,6 +350,7 @@ const FIELD_SETS = {
"toolDefinitions",
"toolCalls",
"toolCallNames",
+ "usagePricingTierId",
"usagePricingTierName",
],
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 4f9f90cbb7..09ea87bae3 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -342,8 +342,16 @@ export const getObservationsForTraceFromEventsTable = async (params: {
projectId: string;
traceId: string;
timestamp?: Date;
+ selectIOAndMetadata?: boolean;
+ selectToolData?: boolean;
}): Promise<{ observations: FullEventsObservations; totalCount: number }> => {
- const { projectId, traceId, timestamp } = params;
+ const {
+ projectId,
+ traceId,
+ timestamp,
+ selectIOAndMetadata = false,
+ selectToolData = false,
+ } = params;
const filter: FilterState = [
{
@@ -373,7 +381,8 @@ export const getObservationsForTraceFromEventsTable = async (params: {
limit: MAX_OBSERVATIONS_PER_TRACE + 1,
offset: 0,
select: "rows",
- selectToolData: false,
+ selectIOAndMetadata,
+ selectToolData,
tags: { kind: "byTraceId" },
},
);
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index d3205f20bd..f6bee7a6c5 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -66,7 +66,7 @@ export const createModelCache = (projectId: string) => {
* @param record - The record to convert (can be null/undefined)
* @returns A new object with all values converted to numbers, or empty object if input is null/undefined
*/
-function convertNumericRecord(
+export function convertNumericRecord(
record: Record<string, number> | null | undefined,
): Record<string, number> {
if (!record) return {};
@@ -268,6 +268,9 @@ export function convertObservationPartial(
outputCost: reducedCostDetails.output,
totalCost: reducedCostDetails.total,
}),
+ ...(record.provided_usage_details !== undefined && {
+ providedUsageDetails: convertNumericRecord(record.provided_usage_details),
+ }),
...(record.provided_cost_details !== undefined && {
providedCostDetails: convertNumericRecord(record.provided_cost_details),
}),
@@ -358,6 +361,7 @@ export function convertObservationPartial(
promptVersion: partial.promptVersion ?? null,
latency: partial.latency ?? null,
timeToFirstToken: partial.timeToFirstToken ?? null,
+ providedUsageDetails: partial.providedUsageDetails ?? {},
usageDetails: partial.usageDetails ?? {},
costDetails: partial.costDetails ?? {},
providedCostDetails: partial.providedCostDetails ?? {},
diff --git a/web/src/__tests__/server/build-trace-export.servertest.ts b/web/src/__tests__/server/build-trace-export.servertest.ts
new file mode 100644
index 0000000000..453ac0ac8f
--- /dev/null
+++ b/web/src/__tests__/server/build-trace-export.servertest.ts
@@ -0,0 +1,466 @@
+import { LangfuseNotFoundError, UnauthorizedError } from "@langfuse/shared";
+import { env } from "@langfuse/shared/src/env";
+import { beforeEach, afterAll, describe, expect, it, vi } from "vitest";
+import {
+ buildTraceExport,
+ TraceDownloadTooLargeError,
+ type TraceExportSession,
+} from "@/src/features/traces/server/buildTraceExport";
+
+const {
+ mockGetTraceByIdFromEventsTable,
+ mockGetObservationsCountFromEventsTable,
+ mockGetObservationsForTraceFromEventsTable,
+ mockGetScoresAndCorrectionsForTraces,
+ mockTraceSessionFindFirst,
+ mockProjectFindFirst,
+ mockSendAdminAccessWebhook,
+} = vi.hoisted(() => ({
+ mockGetTraceByIdFromEventsTable: vi.fn(),
+ mockGetObservationsCountFromEventsTable: vi.fn(),
+ mockGetObservationsForTraceFromEventsTable: vi.fn(),
+ mockGetScoresAndCorrectionsForTraces: vi.fn(),
+ mockTraceSessionFindFirst: vi.fn(),
+ mockProjectFindFirst: vi.fn(),
+ mockSendAdminAccessWebhook: vi.fn(),
+}));
+
+vi.mock("@langfuse/shared/src/server", async () => ({
+ ...(await vi.importActual("@langfuse/shared/src/server")),
+ getTraceByIdFromEventsTable: (...args: unknown[]) =>
+ mockGetTraceByIdFromEventsTable(...args),
+ getObservationsCountFromEventsTable: (...args: unknown[]) =>
+ mockGetObservationsCountFromEventsTable(...args),
+ getObservationsForTraceFromEventsTable: (...args: unknown[]) =>
+ mockGetObservationsForTraceFromEventsTable(...args),
+ getScoresAndCorrectionsForTraces: (...args: unknown[]) =>
+ mockGetScoresAndCorrectionsForTraces(...args),
+}));
+
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: {
+ traceSession: {
+ findFirst: (...args: unknown[]) => mockTraceSessionFindFirst(...args),
+ },
+ project: {
+ findFirst: (...args: unknown[]) => mockProjectFindFirst(...args),
+ },
+ },
+}));
+
+vi.mock("../../server/adminAccessWebhook", () => ({
+ sendAdminAccessWebhook: (...args: unknown[]) =>
+ mockSendAdminAccessWebhook(...args),
+}));
+
+const projectId = "project-1";
+const traceId = "trace-1";
+const traceTimestamp = new Date("2024-01-01T00:00:00.000Z");
+const observationStartTimeFilter = new Date(
+ traceTimestamp.getTime() - 60 * 60 * 1000,
+);
+
+const makeSession = (overrides?: {
+ admin?: boolean;
+ projects?: Array<{ id: string }>;
+}): TraceExportSession => ({
+ user: {
+ email: "[email protected]",
+ admin: overrides?.admin ?? false,
+ organizations: [
+ {
+ projects: overrides?.projects ?? [{ id: projectId }],
+ },
+ ],
+ },
+});
+
+const makeTrace = (overrides?: Record<string, unknown>) => ({
+ id: traceId,
+ name: "Trace 1",
+ timestamp: traceTimestamp,
+ environment: "default",
+ tags: [],
+ bookmarked: false,
+ public: false,
+ release: null,
+ version: null,
+ input: '{"prompt":"hello"}',
+ output: '{"answer":"world"}',
+ metadata: { foo: "bar" },
+ createdAt: new Date("2024-01-01T00:00:00.000Z"),
+ updatedAt: new Date("2024-01-01T00:00:00.000Z"),
+ sessionId: null,
+ userId: null,
+ projectId,
+ ...overrides,
+});
+
+const makeObservation = (overrides?: Record<string, unknown>) => ({
+ id: "obs-1",
+ traceId,
+ projectId,
+ userId: null,
+ sessionId: null,
+ environment: "default",
+ type: "SPAN",
+ startTime: new Date("2024-01-01T00:00:01.000Z"),
+ endTime: new Date("2024-01-01T00:00:02.000Z"),
+ name: "Observation 1",
+ metadata: { key: "value" },
+ parentObservationId: null,
+ level: "DEFAULT",
+ statusMessage: null,
+ version: null,
+ createdAt: new Date("2024-01-01T00:00:01.000Z"),
+ updatedAt: new Date("2024-01-01T00:00:02.000Z"),
+ model: null,
+ internalModelId: null,
+ modelParameters: null,
+ input: '{"input":"secret"}',
+ output: '{"output":"secret"}',
+ completionStartTime: null,
+ promptId: null,
+ promptName: null,
+ promptVersion: null,
+ usageDetails: { input: 90, output: 45, total: 135 },
+ costDetails: { total: 1.23 },
+ providedCostDetails: { total: 1.5 },
+ providedUsageDetails: { input: 100, output: 50, total: 150 },
+ totalCost: null,
+ usagePricingTierId: null,
+ usagePricingTierName: null,
+ toolDefinitions: null,
+ toolCalls: null,
+ toolCallNames: null,
+ ...overrides,
+});
+
+const makeScore = (overrides?: Record<string, unknown>) => ({
+ id: "score-1",
+ projectId,
+ environment: "default",
+ name: "politeness",
+ value: 1,
+ source: "EVAL",
+ authorUserId: null,
+ comment: "helpful",
+ metadata: { target_trace_id: traceId },
+ configId: null,
+ queueId: null,
+ executionTraceId: "exec-1",
+ createdAt: new Date("2024-01-01T00:00:03.000Z"),
+ updatedAt: new Date("2024-01-01T00:00:04.000Z"),
+ timestamp: new Date("2024-01-01T00:00:05.000Z"),
+ traceId,
+ sessionId: null,
+ datasetRunId: null,
+ observationId: null,
+ longStringValue: "",
+ stringValue: null,
+ dataType: "NUMERIC",
+ ...overrides,
+});
+
+describe("buildTraceExport", () => {
+ const originalObservationLimit =
+ env.LANGFUSE_API_TRACE_OBSERVATIONS_SIZE_LIMIT_BYTES;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ env.LANGFUSE_API_TRACE_OBSERVATIONS_SIZE_LIMIT_BYTES =
+ originalObservationLimit;
+ mockGetTraceByIdFromEventsTable.mockResolvedValue(makeTrace());
+ mockGetObservationsCountFromEventsTable.mockResolvedValue(1);
+ mockGetObservationsForTraceFromEventsTable.mockResolvedValue({
+ observations: [makeObservation()],
+ totalCount: 1,
+ });
+ mockGetScoresAndCorrectionsForTraces.mockResolvedValue([makeScore()]);
+ mockTraceSessionFindFirst.mockResolvedValue(null);
+ mockProjectFindFirst.mockResolvedValue({ orgId: "org-1" });
+ });
+
+ afterAll(() => {
+ env.LANGFUSE_API_TRACE_OBSERVATIONS_SIZE_LIMIT_BYTES =
+ originalObservationLimit;
+ });
+
+ it("builds an export using full observation data for smaller traces", async () => {
+ const result = await buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession(),
+ });
+
+ expect(mockGetTraceByIdFromEventsTable).toHaveBeenCalledWith({
+ traceId,
+ projectId,
+ renderingProps: {
+ truncated: true,
+ shouldJsonParse: false,
+ },
+ clickhouseFeatureTag: "tracing-download",
+ });
+ expect(mockGetObservationsCountFromEventsTable).toHaveBeenCalledWith({
+ projectId,
+ filter: [
+ { type: "string", operator: "=", column: "traceId", value: traceId },
+ {
+ type: "datetime",
+ operator: ">=",
+ column: "startTime",
+ value: observationStartTimeFilter,
+ },
+ ],
+ });
+ expect(mockGetObservationsForTraceFromEventsTable).toHaveBeenCalledWith({
+ traceId,
+ projectId,
+ timestamp: traceTimestamp,
+ selectIOAndMetadata: true,
+ selectToolData: true,
+ });
+ expect(mockGetObservationsForTraceFromEventsTable).toHaveBeenCalledTimes(1);
+ expect(mockGetScoresAndCorrectionsForTraces).toHaveBeenCalledWith({
+ projectId,
+ traceIds: [traceId],
+ timestamp: traceTimestamp,
+ });
+ expect(result.scores[0]).not.toHaveProperty("longStringValue");
+ expect(result.scores[0]).not.toHaveProperty("queueId");
+ expect(result.scores[0]).not.toHaveProperty("executionTraceId");
+ expect(result).toMatchObject({
+ scores: [
+ expect.objectContaining({
+ id: "score-1",
+ traceId,
+ value: 1,
+ dataType: "NUMERIC",
+ }),
+ ],
+ observations: [
+ expect.objectContaining({
+ id: "obs-1",
+ traceId,
+ traceName: "Trace 1",
+ tags: [],
+ bookmarked: false,
+ public: false,
+ }),
+ ],
+ });
+ });
+
+ it("maps correction score text into stringValue without leaking internal fields", async () => {
+ mockGetScoresAndCorrectionsForTraces.mockResolvedValue([
+ makeScore({
+ dataType: "CORRECTION",
+ value: 0,
+ stringValue: null,
+ longStringValue: "corrected output",
+ queueId: "queue-1",
+ executionTraceId: "exec-1",
+ }),
+ ]);
+
+ const result = await buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession(),
+ });
+
+ expect(result.scores).toEqual([
+ expect.objectContaining({
+ id: "score-1",
+ traceId,
+ dataType: "CORRECTION",
+ value: 0,
+ stringValue: "corrected output",
+ }),
+ ]);
+ expect(result.scores[0]).not.toHaveProperty("longStringValue");
+ expect(result.scores[0]).not.toHaveProperty("queueId");
+ expect(result.scores[0]).not.toHaveProperty("executionTraceId");
+ });
+
+ it("keeps text score content in stringValue", async () => {
+ mockGetScoresAndCorrectionsForTraces.mockResolvedValue([
+ makeScore({
+ dataType: "TEXT",
+ value: 0,
+ stringValue: "helpful response",
+ }),
+ ]);
+
+ const result = await buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession(),
+ });
+
+ expect(result.scores).toEqual([
+ expect.objectContaining({
+ id: "score-1",
+ traceId,
+ dataType: "TEXT",
+ stringValue: "helpful response",
+ }),
+ ]);
+ expect(result.scores[0]).not.toHaveProperty("value");
+ expect(result.scores[0]).not.toHaveProperty("longStringValue");
+ });
+
+ it("omits IO, metadata, toolDefinitions, and toolCalls for large trace exports", async () => {
+ mockGetObservationsCountFromEventsTable.mockResolvedValue(350);
+ mockGetObservationsForTraceFromEventsTable.mockResolvedValue({
+ observations: Array.from({ length: 350 }, (_, idx) => ({
+ ...makeObservation(),
+ id: `obs-${idx + 1}`,
+ toolCallNames: ["read_file", "write_file"],
+ })),
+ totalCount: 350,
+ });
+
+ const result = await buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession(),
+ });
+
+ expect(mockGetObservationsForTraceFromEventsTable).toHaveBeenCalledWith({
+ traceId,
+ projectId,
+ timestamp: traceTimestamp,
+ selectIOAndMetadata: false,
+ selectToolData: false,
+ });
+ expect(result.observations).toHaveLength(350);
+ expect(result.observations[0]).not.toHaveProperty("input");
+ expect(result.observations[0]).not.toHaveProperty("output");
+ expect(result.observations[0]).not.toHaveProperty("metadata");
+ expect(result.observations[0]).not.toHaveProperty("toolDefinitions");
+ expect(result.observations[0]).not.toHaveProperty("toolCalls");
+ expect(result.observations[0]).toHaveProperty("toolCallNames", [
+ "read_file",
+ "write_file",
+ ]);
+ });
+
+ it("reemits the observation payload limit error as a download-safe error", async () => {
+ mockGetObservationsCountFromEventsTable.mockResolvedValue(10);
+ env.LANGFUSE_API_TRACE_OBSERVATIONS_SIZE_LIMIT_BYTES = 100;
+ mockGetObservationsForTraceFromEventsTable.mockResolvedValue({
+ observations: [
+ makeObservation({
+ input: "x".repeat(60),
+ output: "y".repeat(60),
+ metadata: { key: "z".repeat(60) },
+ }),
+ ],
+ totalCount: 1,
+ });
+
+ await expect(
+ buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession(),
+ }),
+ ).rejects.toBeInstanceOf(TraceDownloadTooLargeError);
+ });
+
+ it("throws a not-found error when the trace is missing", async () => {
+ mockGetTraceByIdFromEventsTable.mockResolvedValue(null);
+
+ await expect(
+ buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession(),
+ }),
+ ).rejects.toBeInstanceOf(LangfuseNotFoundError);
+ });
+
+ it("throws an unauthorized error when the user cannot read the trace", async () => {
+ await expect(
+ buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession({ projects: [{ id: "other-project" }] }),
+ }),
+ ).rejects.toBeInstanceOf(UnauthorizedError);
+ });
+
+ it("allows unauthenticated access to public traces", async () => {
+ mockGetTraceByIdFromEventsTable.mockResolvedValue(
+ makeTrace({ public: true }),
+ );
+
+ const result = await buildTraceExport({
+ traceId,
+ projectId,
+ session: null,
+ });
+
+ expect(result).toMatchObject({
+ observations: [
+ expect.objectContaining({
+ id: "obs-1",
+ traceId,
+ public: true,
+ }),
+ ],
+ });
+ });
+
+ it("allows unauthenticated access to traces in public sessions", async () => {
+ mockGetTraceByIdFromEventsTable.mockResolvedValue(
+ makeTrace({ public: false, sessionId: "trace-session-1" }),
+ );
+ mockTraceSessionFindFirst.mockResolvedValue({ public: true });
+
+ const result = await buildTraceExport({
+ traceId,
+ projectId,
+ session: null,
+ });
+
+ expect(mockTraceSessionFindFirst).toHaveBeenCalledWith({
+ where: {
+ id: "trace-session-1",
+ projectId,
+ },
+ select: {
+ public: true,
+ },
+ });
+ expect(result).toMatchObject({
+ observations: [expect.objectContaining({ id: "obs-1", traceId })],
+ });
+ });
+
+ it("denies unauthenticated access to private traces", async () => {
+ await expect(
+ buildTraceExport({
+ traceId,
+ projectId,
+ session: null,
+ }),
+ ).rejects.toBeInstanceOf(UnauthorizedError);
+ });
+
+ it("notifies on admin access", async () => {
+ await buildTraceExport({
+ traceId,
+ projectId,
+ session: makeSession({ admin: true, projects: [] }),
+ });
+
+ expect(mockSendAdminAccessWebhook).toHaveBeenCalledWith({
+ email: "[email protected]",
+ projectId,
+ orgId: "org-1",
+ });
+ });
+});
diff --git a/web/src/__tests__/server/event-query-builder.servertest.ts b/web/src/__tests__/server/event-query-builder.servertest.ts
index 0c04bc2989..7e6ae25ed9 100644
--- a/web/src/__tests__/server/event-query-builder.servertest.ts
+++ b/web/src/__tests__/server/event-query-builder.servertest.ts
@@ -124,7 +124,7 @@ describe("CTEQueryBuilder", () => {
});
describe("EventsQueryBuilder", () => {
- it("should allow list queries to omit tool payload columns", () => {
+ it("should allow list queries to omit heavy tool payload columns while keeping tool call names", () => {
const slimQuery = new EventsQueryBuilder({
projectId: "test-project",
})
@@ -139,10 +139,43 @@ describe("EventsQueryBuilder", () => {
expect(slimQuery).not.toContain('e.tool_definitions as "tool_definitions"');
expect(slimQuery).not.toContain('e.tool_calls as "tool_calls"');
- expect(slimQuery).not.toContain('e.tool_call_names as "tool_call_names"');
+ expect(slimQuery).toContain('e.tool_call_names as "tool_call_names"');
expect(defaultQuery).toContain('e.tool_definitions as "tool_definitions"');
expect(defaultQuery).toContain('e.tool_calls as "tool_calls"');
expect(defaultQuery).toContain('e.tool_call_names as "tool_call_names"');
});
+
+ it("should include pricing tier fields in observation list, detail, usage, and export field sets", () => {
+ const buildQuery = (
+ ...fieldSets: Parameters<EventsQueryBuilder["selectFieldSet"]>
+ ) =>
+ new EventsQueryBuilder({
+ projectId: "test-project",
+ })
+ .selectFieldSet(...fieldSets)
+ .buildWithParams().query;
+
+ const listQuery = buildQuery("base", "calculated");
+ const slimListQuery = buildQuery("baseWithoutTools", "calculated");
+ const byIdQuery = buildQuery(
+ "byIdBase",
+ "byIdModel",
+ "byIdPrompt",
+ "byIdTimestamps",
+ );
+ const usageQuery = buildQuery("core", "usage");
+ const exportQuery = buildQuery("export");
+
+ [listQuery, slimListQuery, byIdQuery, usageQuery, exportQuery].forEach(
+ (query) => {
+ expect(query).toContain(
+ 'e.usage_pricing_tier_id as "usage_pricing_tier_id"',
+ );
+ expect(query).toContain(
+ 'e.usage_pricing_tier_name as "usage_pricing_tier_name"',
+ );
+ },
+ );
+ });
});
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index a87400ceb4..c97c1db568 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -1,6 +1,7 @@
import {
createEvent,
createEventsCh,
+ getObservationsForTraceFromEventsTable,
getObservationsWithModelDataFromEventsTable,
getObservationsCountFromEventsTable,
getObservationByIdFromEventsTable,
@@ -1716,6 +1717,42 @@ describe("Clickhouse Events Repository Test", () => {
});
});
+ maybe("getObservationsForTraceFromEventsTable", () => {
+ it("should return usage pricing tier fields even when tool payloads are omitted", async () => {
+ const traceId = randomUUID();
+ const generationId = randomUUID();
+
+ await createEventsCh([
+ createEvent({
+ id: generationId,
+ span_id: generationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-trace-pricing-tier-export",
+ usage_pricing_tier_id: "tier-enterprise",
+ usage_pricing_tier_name: "Enterprise",
+ }),
+ ]);
+
+ const { observations, totalCount } =
+ await getObservationsForTraceFromEventsTable({
+ traceId,
+ projectId,
+ selectIOAndMetadata: false,
+ selectToolData: false,
+ });
+
+ expect(totalCount).toBe(1);
+ expect(observations).toHaveLength(1);
+ expect(observations[0]).toMatchObject({
+ id: generationId,
+ usagePricingTierId: "tier-enterprise",
+ usagePricingTierName: "Enterprise",
+ });
+ });
+ });
+
maybe("getObservationsFromEventsTableForPublicApi", () => {
it("should return observations with pagination", async () => {
const uniqueProjectId = randomUUID();
diff --git a/web/src/__tests__/server/trace-download-api.servertest.ts b/web/src/__tests__/server/trace-download-api.servertest.ts
new file mode 100644
index 0000000000..10a9fb4af2
--- /dev/null
+++ b/web/src/__tests__/server/trace-download-api.servertest.ts
@@ -0,0 +1,177 @@
+/** @vitest-environment node */
+import type { NextApiRequest, NextApiResponse } from "next";
+import { createMocks } from "node-mocks-http";
+import { LangfuseNotFoundError, UnauthorizedError } from "@langfuse/shared";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import handler from "../../pages/api/traces/[traceId]/download";
+import { TraceDownloadTooLargeError } from "../../features/traces/server/buildTraceExport";
+
+const { mockGetServerAuthSession, mockBuildTraceExport } = vi.hoisted(() => ({
+ mockGetServerAuthSession: vi.fn(),
+ mockBuildTraceExport: vi.fn(),
+}));
+
+vi.mock("../../server/auth", () => ({
+ getServerAuthSession: (...args: unknown[]) =>
+ mockGetServerAuthSession(...args),
+}));
+
+vi.mock("../../features/traces/server/buildTraceExport", async () => ({
+ ...(await vi.importActual("../../features/traces/server/buildTraceExport")),
+ buildTraceExport: (...args: unknown[]) => mockBuildTraceExport(...args),
+}));
+
+const projectId = "project-1";
+
+const createGetMocks = (query: Record<string, string | string[] | undefined>) =>
+ createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ query,
+ });
+
+describe("GET /api/traces/[traceId]/download", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetServerAuthSession.mockResolvedValue({
+ user: {
+ email: "[email protected]",
+ admin: false,
+ organizations: [{ projects: [{ id: projectId }] }],
+ },
+ });
+ mockBuildTraceExport.mockResolvedValue({
+ scores: [{ id: "score-1", traceId: "trace-1", observationId: null }],
+ observations: [{ id: "obs-1", traceId: "trace-1" }],
+ });
+ });
+
+ it("delegates unauthenticated requests to buildTraceExport", async () => {
+ mockGetServerAuthSession.mockResolvedValue(null);
+ const { req, res } = createGetMocks({
+ traceId: "trace-1",
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(mockBuildTraceExport).toHaveBeenCalledWith({
+ traceId: "trace-1",
+ projectId,
+ session: null,
+ });
+ expect(res._getStatusCode()).toBe(200);
+ });
+
+ it("returns 401 for malformed authenticated sessions", async () => {
+ mockGetServerAuthSession.mockResolvedValue({
+ user: {
+ email: "[email protected]",
+ },
+ });
+ const { req, res } = createGetMocks({
+ traceId: "trace-1",
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(401);
+ });
+
+ it("returns 400 for invalid params", async () => {
+ const { req, res } = createGetMocks({
+ traceId: "",
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ });
+
+ it("returns attachment headers and the log-view export payload", async () => {
+ const { req, res } = createGetMocks({
+ traceId: "trace-1",
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(mockBuildTraceExport).toHaveBeenCalledWith({
+ traceId: "trace-1",
+ projectId,
+ session: expect.any(Object),
+ });
+ expect(res._getStatusCode()).toBe(200);
+ expect(res.getHeader("Content-Disposition")).toBe(
+ "attachment; filename=\"trace-export.json\"; filename*=UTF-8''trace-trace-1.json",
+ );
+ expect(JSON.parse(res._getData())).toMatchObject({
+ scores: [{ id: "score-1", traceId: "trace-1", observationId: null }],
+ observations: [{ id: "obs-1", traceId: "trace-1" }],
+ });
+ });
+
+ it("encodes quoted trace ids in the attachment filename", async () => {
+ mockBuildTraceExport.mockResolvedValue({
+ scores: [{ id: "score-1", traceId: 'foo"bar', observationId: null }],
+ observations: [{ id: "obs-1", traceId: 'foo"bar' }],
+ });
+
+ const { req, res } = createGetMocks({
+ traceId: 'foo"bar',
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(res.getHeader("Content-Disposition")).toBe(
+ "attachment; filename=\"trace-export.json\"; filename*=UTF-8''trace-foo%22bar.json",
+ );
+ });
+
+ it("returns 404 when the trace does not exist", async () => {
+ mockBuildTraceExport.mockRejectedValue(
+ new LangfuseNotFoundError("Trace not found"),
+ );
+ const { req, res } = createGetMocks({
+ traceId: "trace-1",
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(404);
+ });
+
+ it("returns 401 when the trace is unauthorized", async () => {
+ mockBuildTraceExport.mockRejectedValue(
+ new UnauthorizedError("Unauthorized"),
+ );
+ const { req, res } = createGetMocks({
+ traceId: "trace-1",
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(401);
+ });
+
+ it("returns a client-safe size-limit error for full exports", async () => {
+ mockBuildTraceExport.mockRejectedValue(
+ new TraceDownloadTooLargeError("Observations in trace are too large"),
+ );
+ const { req, res } = createGetMocks({
+ traceId: "trace-1",
+ projectId,
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(422);
+ expect(JSON.parse(res._getData()).message).toContain(
+ "Observations in trace are too large",
+ );
+ });
+});
diff --git a/web/src/components/trace/components/TraceLogView/LogViewToolbar.tsx b/web/src/components/trace/components/TraceLogView/LogViewToolbar.tsx
index 81b1de4cc9..a87f145648 100644
--- a/web/src/components/trace/components/TraceLogView/LogViewToolbar.tsx
+++ b/web/src/components/trace/components/TraceLogView/LogViewToolbar.tsx
@@ -47,12 +47,14 @@ export interface LogViewToolbarProps {
onToggleExpandAll?: () => void;
/** Whether all rows are expanded */
allRowsExpanded?: boolean;
+ /** Whether copy/download action is currently loading */
+ isCopyOrDownloadLoading?: boolean;
+ /** Whether copy/download uses cached I/O only (doesn't load all) */
+ isCopyOrDownloadCacheOnly?: boolean;
/** Callback to copy JSON */
onCopyJson?: () => void;
/** Callback to download JSON */
onDownloadJson?: () => void;
- /** Whether download/copy uses cached I/O only (doesn't load all) */
- isDownloadCacheOnly?: boolean;
/** Current view type (pretty/json/json-beta) */
currentView?: "pretty" | "json" | "json-beta";
/** Whether indent visualization is enabled */
@@ -65,8 +67,6 @@ export interface LogViewToolbarProps {
showMilliseconds?: boolean;
/** Callback to toggle milliseconds display */
onToggleMilliseconds?: () => void;
- /** Whether download/copy is currently loading */
- isDownloadLoading?: boolean;
}
/**
@@ -81,19 +81,21 @@ export const LogViewToolbar = memo(function LogViewToolbar({
onToggleExpandAll,
allRowsExpanded,
onCopyJson,
+ isCopyOrDownloadLoading = false,
onDownloadJson,
- isDownloadCacheOnly = false,
+ isCopyOrDownloadCacheOnly = false,
currentView = "pretty",
indentEnabled = false,
indentDisabled = false,
onToggleIndent,
showMilliseconds = false,
onToggleMilliseconds,
- isDownloadLoading = false,
}: LogViewToolbarProps) {
const [isCopied, setIsCopied] = useState(false);
const handleCopyClick = () => {
+ if (isCopyOrDownloadLoading) return;
+
setIsCopied(true);
onCopyJson?.();
setTimeout(() => setIsCopied(false), 1000);
@@ -240,10 +242,12 @@ export const LogViewToolbar = memo(function LogViewToolbar({
variant="ghost"
size="icon"
className="h-7 w-7"
- onClick={isDownloadLoading ? undefined : handleCopyClick}
- disabled={isDownloadLoading}
+ onClick={
+ isCopyOrDownloadLoading ? undefined : handleCopyClick
+ }
+ disabled={isCopyOrDownloadLoading}
>
- {isDownloadLoading ? (
+ {isCopyOrDownloadLoading ? (
<Spinner size="xs" />
) : isCopied ? (
<Check className="h-3.5 w-3.5" />
@@ -253,15 +257,15 @@ export const LogViewToolbar = memo(function LogViewToolbar({
</Button>
</TooltipTrigger>
<TooltipContent>
- {isDownloadLoading
+ {isCopyOrDownloadLoading
? "Loading data..."
- : isDownloadCacheOnly
+ : isCopyOrDownloadCacheOnly
? "Copy as JSON (cache only)"
: "Copy as JSON"}
</TooltipContent>
</Tooltip>
</HoverCardTrigger>
- {isDownloadCacheOnly && !isDownloadLoading && (
+ {isCopyOrDownloadCacheOnly && !isCopyOrDownloadLoading && (
<HoverCardContent className="w-64 text-sm" sideOffset={8}>
<p className="font-medium">Cache-only mode</p>
<p className="text-muted-foreground mt-1">
@@ -292,10 +296,12 @@ export const LogViewToolbar = memo(function LogViewToolbar({
variant="ghost"
size="icon"
className="h-7 w-7"
- onClick={isDownloadLoading ? undefined : onDownloadJson}
- disabled={isDownloadLoading}
+ onClick={
+ isCopyOrDownloadLoading ? undefined : onDownloadJson
+ }
+ disabled={isCopyOrDownloadLoading}
>
- {isDownloadLoading ? (
+ {isCopyOrDownloadLoading ? (
<Spinner size="xs" />
) : (
<Download className="h-3.5 w-3.5" />
@@ -303,15 +309,15 @@ export const LogViewToolbar = memo(function LogViewToolbar({
</Button>
</TooltipTrigger>
<TooltipContent>
- {isDownloadLoading
+ {isCopyOrDownloadLoading
? "Loading data..."
- : isDownloadCacheOnly
+ : isCopyOrDownloadCacheOnly
? "Download as JSON (cache only)"
: "Download as JSON"}
</TooltipContent>
</Tooltip>
</HoverCardTrigger>
- {isDownloadCacheOnly && !isDownloadLoading && (
+ {isCopyOrDownloadCacheOnly && !isCopyOrDownloadLoading && (
<HoverCardContent className="w-64 text-sm" sideOffset={8}>
<p className="font-medium">Cache-only mode</p>
<p className="text-muted-foreground mt-1">
diff --git a/web/src/components/trace/components/TraceLogView/TraceLogView.tsx b/web/src/components/trace/components/TraceLogView/TraceLogView.tsx
index 2541a28cf2..5ebfe2af63 100644
--- a/web/src/components/trace/components/TraceLogView/TraceLogView.tsx
+++ b/web/src/components/trace/components/TraceLogView/TraceLogView.tsx
@@ -84,7 +84,7 @@ export const TraceLogView = ({
observations.length >= LOG_VIEW_VIRTUALIZATION_THRESHOLD;
// Determine if download/copy should use cached I/O only (vs loading all)
- const isDownloadCacheOnly =
+ const isCopyOrDownloadCacheOnly =
observations.length >= LOG_VIEW_DOWNLOAD_THRESHOLD;
// Get expanded keys from context (persisted in sessionStorage)
@@ -246,10 +246,10 @@ export const TraceLogView = ({
});
// Download and copy handlers
- const { handleCopyJson, handleDownloadJson, isDownloadOrCopyLoading } =
+ const { handleCopyJson, isActionLoading: isCopyOrDownloadLoading } =
useLogViewDownload({
traceId,
- isDownloadCacheOnly,
+ isCacheOnly: isCopyOrDownloadCacheOnly,
allObservationsData: allObservationsIO.data,
isLoadingAllData: allObservationsIO.isLoading,
failedObservationIds: allObservationsIO.failedObservationIds,
@@ -278,9 +278,8 @@ export const TraceLogView = ({
onToggleExpandAll={handleToggleExpandAll}
allRowsExpanded={allRowsExpanded}
onCopyJson={handleCopyJson}
- onDownloadJson={handleDownloadJson}
- isDownloadCacheOnly={isDownloadCacheOnly}
- isDownloadLoading={isDownloadOrCopyLoading}
+ isCopyOrDownloadLoading={isCopyOrDownloadLoading}
+ isCopyOrDownloadCacheOnly={isCopyOrDownloadCacheOnly}
currentView={currentView}
indentEnabled={indentEnabled}
indentDisabled={indentDisabled}
diff --git a/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts b/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts
index b376c615b7..70e15ae173 100644
--- a/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts
+++ b/web/src/components/trace/components/TraceLogView/useLogViewDownload.ts
@@ -16,7 +16,7 @@ export interface UseLogViewDownloadParams {
/** Trace ID for filename */
traceId: string;
/** Whether to use cached I/O only (vs loading all data) */
- isDownloadCacheOnly: boolean;
+ isCacheOnly: boolean;
/** Already loaded observation data (null if not loaded) */
allObservationsData: ObservationIOData[] | null;
/** Whether data is being loaded by useLogViewAllObservationsIO */
@@ -29,29 +29,19 @@ export interface UseLogViewDownloadParams {
buildDataFromCache: () => ObservationIOData[];
}
-export interface UseLogViewDownloadReturn {
- /** Copy JSON to clipboard handler */
- handleCopyJson: () => Promise<void>;
- /** Download JSON file handler */
- handleDownloadJson: () => Promise<void>;
- /** Whether download/copy operation is in progress */
- isDownloadOrCopyLoading: boolean;
-}
-
/**
* Hook for managing download and copy JSON functionality.
*/
export function useLogViewDownload({
traceId,
- isDownloadCacheOnly,
+ isCacheOnly,
allObservationsData,
isLoadingAllData,
failedObservationIds,
loadAllData,
buildDataFromCache,
-}: UseLogViewDownloadParams): UseLogViewDownloadReturn {
- // Track if we're actively loading for download
- const [isDownloadLoading, setIsDownloadLoading] = useState(false);
+}: UseLogViewDownloadParams) {
+ const [isActionLoading, setIsActionLoading] = useState(false);
// Helper to download JSON data
const downloadJsonData = useCallback(
@@ -71,14 +61,17 @@ export function useLogViewDownload({
// Copy JSON handler - uses cache only or loads all based on threshold
const handleCopyJson = useCallback(async () => {
- if (isDownloadCacheOnly) {
+ if (isCacheOnly) {
// Cache-only mode: build from tree + cache (no fetching)
- setIsDownloadLoading(true);
+ setIsActionLoading(true);
setTimeout(() => {
- const data = buildDataFromCache();
- void copyTextToClipboard(JSON.stringify(data, null, 2));
- toast.success("Copied to clipboard (cache only)");
- setIsDownloadLoading(false);
+ try {
+ const data = buildDataFromCache();
+ void copyTextToClipboard(JSON.stringify(data, null, 2));
+ toast.success("Copied to clipboard (cache only)");
+ } finally {
+ setIsActionLoading(false);
+ }
}, 0);
} else {
// Load all mode: fetch all data if needed
@@ -93,7 +86,7 @@ export function useLogViewDownload({
toast.success("Copied to clipboard");
}
} else {
- setIsDownloadLoading(true);
+ setIsActionLoading(true);
try {
const data = await loadAllData();
void copyTextToClipboard(JSON.stringify(data, null, 2));
@@ -106,12 +99,12 @@ export function useLogViewDownload({
toast.success("Copied to clipboard");
}
} finally {
- setIsDownloadLoading(false);
+ setIsActionLoading(false);
}
}
}
}, [
- isDownloadCacheOnly,
+ isCacheOnly,
allObservationsData,
loadAllData,
buildDataFromCache,
@@ -120,15 +113,18 @@ export function useLogViewDownload({
// Download JSON handler - uses cache only or loads all based on threshold
const handleDownloadJson = useCallback(async () => {
- if (isDownloadCacheOnly) {
+ if (isCacheOnly) {
// Cache-only mode: build from tree + cache (no fetching)
- setIsDownloadLoading(true);
+ setIsActionLoading(true);
// Use setTimeout to allow spinner to render before potentially heavy operation
setTimeout(() => {
- const data = buildDataFromCache();
- downloadJsonData(data);
- toast.success("Downloaded trace data (cache only)");
- setIsDownloadLoading(false);
+ try {
+ const data = buildDataFromCache();
+ downloadJsonData(data);
+ toast.success("Downloaded trace data (cache only)");
+ } finally {
+ setIsActionLoading(false);
+ }
}, 0);
} else {
// Load all mode: fetch all data if needed
@@ -143,7 +139,7 @@ export function useLogViewDownload({
toast.success("Downloaded trace data");
}
} else {
- setIsDownloadLoading(true);
+ setIsActionLoading(true);
try {
const data = await loadAllData();
downloadJsonData(data);
@@ -156,12 +152,12 @@ export function useLogViewDownload({
toast.success("Downloaded trace data");
}
} finally {
- setIsDownloadLoading(false);
+ setIsActionLoading(false);
}
}
}
}, [
- isDownloadCacheOnly,
+ isCacheOnly,
allObservationsData,
loadAllData,
buildDataFromCache,
@@ -169,12 +165,9 @@ export function useLogViewDownload({
failedObservationIds,
]);
- // Loading state for download button
- const isDownloadOrCopyLoading = isDownloadLoading || isLoadingAllData;
-
return {
handleCopyJson,
handleDownloadJson,
- isDownloadOrCopyLoading,
+ isActionLoading: isActionLoading || isLoadingAllData,
};
}
diff --git a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx
index eefe677157..c2fa92cddb 100644
--- a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx
+++ b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx
@@ -13,15 +13,22 @@ import { useSearch } from "../../contexts/SearchContext";
import { useSelection } from "../../contexts/SelectionContext";
import { useTraceData } from "../../contexts/TraceDataContext";
import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import { Command, CommandInput } from "@/src/components/ui/command";
import { Button } from "@/src/components/ui/button";
-import { FoldVertical, UnfoldVertical, Download } from "lucide-react";
+import { FoldVertical, UnfoldVertical, Download, Loader2 } from "lucide-react";
import { StringParam, useQueryParam } from "use-query-params";
import { cn } from "@/src/utils/tailwind";
import { useCallback } from "react";
import { TraceSettingsDropdown } from "../TraceSettingsDropdown";
-import { downloadTraceAsJson } from "../../lib/download-trace";
+import {
+ downloadLegacyTraceAsJson,
+ downloadServerTraceAsJson,
+} from "../../lib/download-trace";
import { TracePanelNavigationButton } from "./TracePanelNavigationButton";
+import { toast } from "sonner";
+import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "@/src/features/traces/shared/traceDownloadConfig";
+import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
interface TracePanelNavigationHeaderProps {
isPanelCollapsed: boolean;
@@ -64,6 +71,7 @@ function TracePanelNavigationHeaderExpanded({
const { expandAll, collapseAll, collapsedNodes } = useSelection();
const { roots, trace, observations } = useTraceData();
const { isGraphViewAvailable } = useTraceGraphData();
+ const { isBetaEnabled } = useV4Beta();
const [viewMode, setViewMode] = useQueryParam("view", StringParam);
const handleSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
@@ -95,12 +103,35 @@ function TracePanelNavigationHeaderExpanded({
}
}, [isEverythingCollapsed, expandAll, collapseAll, getAllNodeIds, roots]);
- const handleDownload = useCallback(() => {
- downloadTraceAsJson({
- trace,
- observations,
- });
- }, [trace, observations]);
+ const [handleDownload, isDownloading] =
+ useWatchedPromiseCallback(async () => {
+ try {
+ if (!isBetaEnabled) {
+ downloadLegacyTraceAsJson({
+ trace,
+ observations,
+ });
+ return;
+ }
+
+ await downloadServerTraceAsJson({
+ traceId: trace.id,
+ projectId: trace.projectId,
+ });
+
+ if (observations.length >= TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD) {
+ toast.warning(
+ `Trace download excludes IO, metadata, toolDefinitions, and toolCalls for traces with ${TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD}+ observations.`,
+ );
+ }
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to download trace JSON",
+ );
+ }
+ }, [isBetaEnabled, observations, trace]);
const isTimelineView = viewMode === "timeline";
@@ -150,10 +181,15 @@ function TracePanelNavigationHeaderExpanded({
variant="ghost"
size="icon"
onClick={handleDownload}
+ disabled={isDownloading}
title="Download trace as JSON"
className="h-7 w-7"
>
- <Download className="h-3.5 w-3.5" />
+ {isDownloading ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Download className="h-3.5 w-3.5" />
+ )}
</Button>
{/* Timeline Toggle Button */}
diff --git a/web/src/components/trace/config/trace-view-config.ts b/web/src/components/trace/config/trace-view-config.ts
index b09f42a291..50c9dbe1e5 100644
--- a/web/src/components/trace/config/trace-view-config.ts
+++ b/web/src/components/trace/config/trace-view-config.ts
@@ -1,3 +1,5 @@
+import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "@/src/features/traces/shared/traceDownloadConfig";
+
/**
* Configuration constants for trace views.
*
@@ -20,7 +22,7 @@ export const TRACE_VIEW_CONFIG = {
* Number of observations above which download uses cached I/O only.
* Above this threshold, only expanded observations include full I/O data.
*/
- downloadThreshold: 350,
+ downloadThreshold: TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD,
/**
* Row heights for virtualization calculations
diff --git a/web/src/components/trace/lib/download-trace.ts b/web/src/components/trace/lib/download-trace.ts
index 4730d6aaa2..7fe5cf4a12 100644
--- a/web/src/components/trace/lib/download-trace.ts
+++ b/web/src/components/trace/lib/download-trace.ts
@@ -1,8 +1,29 @@
-/**
- * Helper function for downloading trace data as JSON
- */
+export interface ServerTraceDownloadParams {
+ traceId: string;
+ projectId: string;
+}
+
+export function buildTraceDownloadUrl({
+ traceId,
+ projectId,
+}: ServerTraceDownloadParams): string {
+ const query = new URLSearchParams({
+ projectId,
+ });
+
+ return `/api/traces/${encodeURIComponent(traceId)}/download?${query.toString()}`;
+}
+
+function hasErrorMessage(value: unknown): value is { message: string } {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "message" in value &&
+ typeof value.message === "string"
+ );
+}
-export interface DownloadTraceAsJsonParams {
+export interface LegacyTraceDownloadParams {
trace: {
id: string;
[key: string]: unknown;
@@ -11,33 +32,54 @@ export interface DownloadTraceAsJsonParams {
filename?: string;
}
-/**
- * Download trace data with observations as JSON file
- *
- * @param params - Configuration object
- * @param params.trace - Trace object to download
- * @param params.observations - Array of observations (can be basic or with full I/O data)
- * @param params.filename - Optional custom filename (defaults to trace-{traceId}.json)
- */
-export function downloadTraceAsJson(params: DownloadTraceAsJsonParams): void {
- const { trace, observations, filename } = params;
-
- const exportData = {
- trace,
- observations,
- };
-
- const jsonString = JSON.stringify(exportData, null, 2);
- const blob = new Blob([jsonString], {
- type: "application/json; charset=utf-8",
- });
+function downloadBlob(params: { blob: Blob; filename: string }) {
+ const { blob, filename } = params;
const url = URL.createObjectURL(blob);
-
const link = document.createElement("a");
link.href = url;
- link.download = filename || `trace-${trace.id}.json`;
+ link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
+
+export async function downloadServerTraceAsJson(
+ params: ServerTraceDownloadParams,
+) {
+ const { traceId, projectId } = params;
+ const response = await fetch(buildTraceDownloadUrl({ traceId, projectId }), {
+ method: "GET",
+ credentials: "same-origin",
+ });
+
+ if (!response.ok) {
+ const errorBody: unknown = await response.json().catch(() => null);
+ throw new Error(
+ hasErrorMessage(errorBody)
+ ? errorBody.message
+ : "Failed to download trace JSON",
+ );
+ }
+
+ const blob = await response.blob();
+ downloadBlob({
+ blob,
+ filename: `trace-${encodeURIComponent(traceId)}.json`,
+ });
+}
+
+export function downloadLegacyTraceAsJson(params: LegacyTraceDownloadParams) {
+ const { trace, observations, filename } = params;
+ const exportData = {
+ trace,
+ observations,
+ };
+
+ downloadBlob({
+ blob: new Blob([JSON.stringify(exportData, null, 2)], {
+ type: "application/json; charset=utf-8",
+ }),
+ filename: filename || `trace-${trace.id}.json`,
+ });
+}
diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.ts
index dde369f220..114adc3717 100644
--- a/web/src/components/trace/lib/helpers.ts
+++ b/web/src/components/trace/lib/helpers.ts
@@ -469,39 +469,3 @@ export function buildTraceUiData(
return { tree, hiddenObservationsCount, searchItems: out, nodeMap };
}
-
-/**
- * Download trace data with optionally observations as JSON file
- * @param trace - Trace object to download
- * @param observations - Array of observations (can be basic or with full I/O data)
- * @param filename - Optional custom filename (defaults to trace-{traceId}.json)
- */
-export function downloadTraceAsJson(params: {
- trace: {
- id: string;
- [key: string]: unknown;
- };
- observations: unknown[];
- filename?: string;
-}) {
- const { trace, observations, filename } = params;
-
- const exportData = {
- trace,
- observations,
- };
-
- const jsonString = JSON.stringify(exportData, null, 2);
- const blob = new Blob([jsonString], {
- type: "application/json; charset=utf-8",
- });
- const url = URL.createObjectURL(blob);
-
- const link = document.createElement("a");
- link.href = url;
- link.download = filename || `trace-${trace.id}.json`;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-}
diff --git a/web/src/components/trace/lib/tree-building.clienttest.ts b/web/src/components/trace/lib/tree-building.clienttest.ts
index 3f707fb496..c535ca2744 100644
--- a/web/src/components/trace/lib/tree-building.clienttest.ts
+++ b/web/src/components/trace/lib/tree-building.clienttest.ts
@@ -45,6 +45,7 @@ const createMockObservation = (
inputUsage: 0,
outputUsage: 0,
totalUsage: 0,
+ providedUsageDetails: {},
usageDetails: {},
costDetails: {},
providedCostDetails: {},
diff --git a/web/src/features/events/lib/eventsToTraceAdapter.clienttest.ts b/web/src/features/events/lib/eventsToTraceAdapter.clienttest.ts
index e4d1e9c222..d9d50fa48b 100644
--- a/web/src/features/events/lib/eventsToTraceAdapter.clienttest.ts
+++ b/web/src/features/events/lib/eventsToTraceAdapter.clienttest.ts
@@ -7,63 +7,65 @@ type EventInput = Parameters<
typeof adaptEventsToTraceFormat
>[0]["events"][number];
-const createEvent = (overrides: Partial<EventInput> = {}): EventInput => ({
- id: "obs-1",
- traceId: "trace-1",
- projectId: "project-1",
- environment: "default",
- type: "SPAN",
- startTime: baseDate,
- endTime: null,
- name: "Root span",
- metadata: "{}",
- parentObservationId: null,
- level: "DEFAULT",
- statusMessage: null,
- version: null,
- createdAt: baseDate,
- updatedAt: baseDate,
- model: null,
- internalModelId: null,
- modelParameters: null,
- input: null,
- output: null,
- completionStartTime: null,
- promptId: null,
- promptName: null,
- promptVersion: null,
- latency: null,
- timeToFirstToken: null,
- usageDetails: {},
- costDetails: {},
- providedCostDetails: {},
- inputCost: null,
- outputCost: null,
- totalCost: null,
- inputUsage: 0,
- outputUsage: 0,
- totalUsage: 0,
- usagePricingTierId: null,
- usagePricingTierName: null,
- toolDefinitions: null,
- toolCalls: null,
- toolCallNames: null,
- userId: null,
- sessionId: null,
- traceName: "Trace name",
- release: null,
- tags: [],
- bookmarked: false,
- public: false,
- traceTags: [],
- traceTimestamp: baseDate,
- toolDefinitionsCount: null,
- toolCallsCount: null,
- inputPrice: null,
- outputPrice: null,
- totalPrice: null,
- ...overrides,
-});
+const createEvent = (overrides: Partial<EventInput> = {}) =>
+ ({
+ id: "obs-1",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "default",
+ type: "SPAN",
+ startTime: baseDate,
+ endTime: null,
+ name: "Root span",
+ metadata: "{}",
+ parentObservationId: null,
+ level: "DEFAULT",
+ statusMessage: null,
+ version: null,
+ createdAt: baseDate,
+ updatedAt: baseDate,
+ model: null,
+ internalModelId: null,
+ modelParameters: null,
+ input: null,
+ output: null,
+ completionStartTime: null,
+ promptId: null,
+ promptName: null,
+ promptVersion: null,
+ latency: null,
+ timeToFirstToken: null,
+ usageDetails: {},
+ costDetails: {},
+ providedCostDetails: {},
+ providedUsageDetails: {},
+ inputCost: null,
+ outputCost: null,
+ totalCost: null,
+ inputUsage: 0,
+ outputUsage: 0,
+ totalUsage: 0,
+ usagePricingTierId: null,
+ usagePricingTierName: null,
+ toolDefinitions: null,
+ toolCalls: null,
+ toolCallNames: null,
+ userId: null,
+ sessionId: null,
+ traceName: "Trace name",
+ release: null,
+ tags: [],
+ bookmarked: false,
+ public: false,
+ traceTags: [],
+ traceTimestamp: baseDate,
+ toolDefinitionsCount: null,
+ toolCallsCount: null,
+ inputPrice: null,
+ outputPrice: null,
+ totalPrice: null,
+ ...overrides,
+ }) satisfies EventInput;
describe("adaptEventsToTraceFormat", () => {
it("does not double-stringify root I/O already stringified for tRPC", () => {
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index 1c917893ad..fc1e1196da 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -132,6 +132,7 @@ export const transformDbToApiObservation = (
const totalTokens = reducedUsageDetails.total ?? 0;
const {
+ providedUsageDetails,
providedCostDetails,
internalModelId,
diff --git a/web/src/features/traces/server/buildTraceExport.ts b/web/src/features/traces/server/buildTraceExport.ts
new file mode 100644
index 0000000000..9ba64edd81
--- /dev/null
+++ b/web/src/features/traces/server/buildTraceExport.ts
@@ -0,0 +1,306 @@
+import {
+ BaseError,
+ LangfuseNotFoundError,
+ ScoreDataTypeEnum,
+ UnauthorizedError,
+} from "@langfuse/shared";
+import {
+ getScoresAndCorrectionsForTraces,
+ getObservationsCountFromEventsTable,
+ getObservationsForTraceFromEventsTable,
+ getTraceByIdFromEventsTable,
+} from "@langfuse/shared/src/server";
+import { env } from "@langfuse/shared/src/env";
+import { prisma } from "@langfuse/shared/src/db";
+import { sendAdminAccessWebhook } from "@/src/server/adminAccessWebhook";
+import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "../shared/traceDownloadConfig";
+
+export type TraceExportSession = {
+ user: {
+ email: string;
+ admin?: boolean;
+ organizations: Array<{
+ projects: Array<{
+ id: string;
+ }>;
+ }>;
+ };
+};
+
+export type TraceExportAccessSession = TraceExportSession | null;
+
+export class TraceDownloadTooLargeError extends BaseError {
+ constructor(description = "Observations in trace are too large") {
+ super("TraceDownloadTooLargeError", 422, description, true);
+ }
+}
+
+const getDurationSeconds = (
+ startTime: Date,
+ endTime: Date | null,
+): number | null => {
+ if (!endTime) {
+ return null;
+ }
+
+ return (endTime.getTime() - startTime.getTime()) / 1000;
+};
+
+const hasProjectAccess = (
+ session: TraceExportAccessSession,
+ projectId: string,
+) =>
+ session?.user.organizations.some((organization) =>
+ organization.projects.some((project) => project.id === projectId),
+ ) ?? false;
+
+const getObservationRecordsForTrace = async (params: {
+ traceId: string;
+ projectId: string;
+ timestamp: Date;
+ omitLargeFields: boolean;
+}) => {
+ const { traceId, projectId, timestamp, omitLargeFields } = params;
+
+ return getObservationsForTraceFromEventsTable({
+ traceId,
+ projectId,
+ timestamp,
+ selectIOAndMetadata: !omitLargeFields,
+ selectToolData: !omitLargeFields,
+ });
+};
+
+const getObservationRecordCountForTrace = async (params: {
+ traceId: string;
+ projectId: string;
+ timestamp: Date;
+}) => {
+ const { traceId, projectId, timestamp } = params;
+
+ return getObservationsCountFromEventsTable({
+ projectId,
+ filter: [
+ { type: "string", operator: "=", column: "traceId", value: traceId },
+ {
+ type: "datetime",
+ operator: ">=",
+ column: "startTime",
+ value: new Date(timestamp.getTime() - 60 * 60 * 1000),
+ },
+ ],
+ });
+};
+
+async function getAuthorizedTrace(params: {
+ traceId: string;
+ projectId: string;
+ session: TraceExportAccessSession;
+}) {
+ const { traceId, projectId, session } = params;
+
+ const clickhouseTrace = await getTraceByIdFromEventsTable({
+ traceId,
+ projectId,
+ renderingProps: {
+ truncated: true,
+ shouldJsonParse: false,
+ },
+ clickhouseFeatureTag: "tracing-download",
+ });
+
+ if (!clickhouseTrace) {
+ throw new LangfuseNotFoundError("Trace not found");
+ }
+
+ const traceSession = clickhouseTrace.sessionId
+ ? await prisma.traceSession.findFirst({
+ where: {
+ id: clickhouseTrace.sessionId,
+ projectId,
+ },
+ select: {
+ public: true,
+ },
+ })
+ : null;
+
+ const isSessionPublic = traceSession?.public === true;
+ const isAdmin = session?.user.admin === true;
+ const canReadTrace =
+ clickhouseTrace.public ||
+ isSessionPublic ||
+ isAdmin ||
+ hasProjectAccess(session, projectId);
+
+ if (!canReadTrace) {
+ throw new UnauthorizedError(
+ "User is not a member of this project and this trace is not public",
+ );
+ }
+
+ if (isAdmin) {
+ const dbProject = await prisma.project.findFirst({
+ where: { id: projectId, deletedAt: null },
+ select: { orgId: true },
+ });
+
+ await sendAdminAccessWebhook({
+ email: session.user.email,
+ projectId,
+ orgId: dbProject?.orgId,
+ });
+ }
+
+ return clickhouseTrace;
+}
+
+export async function buildTraceExport({
+ traceId,
+ projectId,
+ session,
+}: {
+ traceId: string;
+ projectId: string;
+ session: TraceExportAccessSession;
+}) {
+ const trace = await getAuthorizedTrace({
+ traceId,
+ projectId,
+ session,
+ });
+
+ const observationRecordCount = await getObservationRecordCountForTrace({
+ traceId,
+ projectId,
+ timestamp: trace.timestamp,
+ });
+ const omitLargeFields =
+ observationRecordCount >= TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD;
+ const observationRecords = await getObservationRecordsForTrace({
+ traceId,
+ projectId,
+ timestamp: trace.timestamp,
+ omitLargeFields,
+ }).then((result) => result.observations);
+
+ if (!omitLargeFields) {
+ // Same size validation as in getObservationsForTrace in observations.ts
+ let payloadSize = 0;
+
+ for (const observation of observationRecords) {
+ for (const key of ["input", "output"] as const) {
+ const value = observation[key];
+
+ if (typeof value === "string") {
+ payloadSize += value.length;
+ }
+ }
+
+ payloadSize += JSON.stringify(observation.metadata).length;
+
+ if (payloadSize >= env.LANGFUSE_API_TRACE_OBSERVATIONS_SIZE_LIMIT_BYTES) {
+ throw new TraceDownloadTooLargeError(
+ `Observations in trace are too large: ${(payloadSize / 1e6).toFixed(2)}MB exceeds limit of ${(env.LANGFUSE_API_TRACE_OBSERVATIONS_SIZE_LIMIT_BYTES / 1e6).toFixed(2)}MB`,
+ );
+ }
+ }
+ }
+
+ const scoreRecords = await getScoresAndCorrectionsForTraces({
+ projectId,
+ traceIds: [traceId],
+ timestamp: trace.timestamp,
+ });
+
+ const scores = scoreRecords.map((score) => ({
+ id: score.id,
+ projectId: score.projectId,
+ environment: score.environment,
+ name: score.name,
+ source: score.source,
+ authorUserId: score.authorUserId,
+ comment: score.comment,
+ metadata: score.metadata ?? null,
+ configId: score.configId,
+ createdAt: score.createdAt.toISOString(),
+ updatedAt: score.updatedAt.toISOString(),
+ timestamp: score.timestamp.toISOString(),
+ traceId: score.traceId,
+ sessionId: score.sessionId,
+ datasetRunId: score.datasetRunId,
+ observationId: score.observationId,
+ dataType: score.dataType,
+ ...(score.dataType !== ScoreDataTypeEnum.TEXT && { value: score.value }),
+ ...(score.dataType === ScoreDataTypeEnum.CATEGORICAL ||
+ score.dataType === ScoreDataTypeEnum.BOOLEAN ||
+ score.dataType === ScoreDataTypeEnum.TEXT ||
+ score.dataType === ScoreDataTypeEnum.CORRECTION
+ ? {
+ stringValue:
+ score.dataType === ScoreDataTypeEnum.CORRECTION
+ ? score.longStringValue
+ : (score.stringValue ?? null),
+ }
+ : {}),
+ }));
+
+ const observations = observationRecords.map((record) => {
+ return {
+ id: record.id,
+ traceId: record.traceId ?? traceId,
+ userId: record.userId ?? null,
+ sessionId: record.sessionId ?? null,
+ projectId: record.projectId,
+ startTime: record.startTime.toISOString(),
+ endTime: record.endTime?.toISOString() ?? null,
+ parentObservationId: record.parentObservationId ?? null,
+ type: record.type,
+ environment: record.environment,
+ name: record.name ?? null,
+ level: record.level ?? null,
+ traceName: record.traceName ?? trace.name ?? "",
+ statusMessage: record.statusMessage ?? null,
+ release: record.release ?? null,
+ version: record.version ?? null,
+ createdAt: record.createdAt.toISOString(),
+ updatedAt: record.updatedAt.toISOString(),
+ model: record.model ?? null,
+ modelParameters: record.modelParameters,
+ internalModelId: record.internalModelId ?? null,
+ completionStartTime: record.completionStartTime?.toISOString() ?? null,
+ promptId: record.promptId ?? null,
+ promptName: record.promptName ?? null,
+ promptVersion: record.promptVersion ?? null,
+ providedUsageDetails: record.providedUsageDetails,
+ latency: getDurationSeconds(record.startTime, record.endTime),
+ timeToFirstToken: getDurationSeconds(
+ record.startTime,
+ record.completionStartTime,
+ ),
+ usageDetails: record.usageDetails,
+ costDetails: record.costDetails,
+ providedCostDetails: record.providedCostDetails,
+ usagePricingTierId: record.usagePricingTierId ?? null,
+ usagePricingTierName: record.usagePricingTierName ?? null,
+ toolCallNames: record.toolCallNames ?? [],
+ tags: trace.tags,
+ bookmarked: trace.bookmarked,
+ public: trace.public,
+ ...(!omitLargeFields
+ ? {
+ toolDefinitions: record.toolDefinitions ?? {},
+ toolCalls: record.toolCalls ?? [],
+ input: record.input,
+ output: record.output,
+ metadata: record.metadata ?? {},
+ }
+ : {}),
+ };
+ });
+
+ return {
+ observations,
+ scores,
+ };
+}
diff --git a/web/src/features/traces/shared/traceDownloadConfig.ts b/web/src/features/traces/shared/traceDownloadConfig.ts
new file mode 100644
index 0000000000..ed99b42573
--- /dev/null
+++ b/web/src/features/traces/shared/traceDownloadConfig.ts
@@ -0,0 +1 @@
+export const TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD = 350;
diff --git a/web/src/hooks/useWatchedPromiseCallback.clienttest.tsx b/web/src/hooks/useWatchedPromiseCallback.clienttest.tsx
new file mode 100644
index 0000000000..f4c240e3e1
--- /dev/null
+++ b/web/src/hooks/useWatchedPromiseCallback.clienttest.tsx
@@ -0,0 +1,152 @@
+import { StrictMode } from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
+
+const createDeferred = <T,>() => {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+
+ return { promise, resolve, reject };
+};
+
+describe("useWatchedPromiseCallback", () => {
+ it("tracks loading state and reuses the in-flight promise", async () => {
+ const deferred = createDeferred<string>();
+ const callback = vi.fn().mockReturnValue(deferred.promise);
+
+ const { result } = renderHook(() =>
+ useWatchedPromiseCallback(callback, []),
+ );
+
+ let firstPromise!: Promise<unknown>;
+ let secondPromise!: Promise<unknown>;
+
+ act(() => {
+ firstPromise = result.current[0]("first");
+ secondPromise = result.current[0]("second");
+ });
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback).toHaveBeenCalledWith("first");
+ expect(secondPromise).toBe(firstPromise);
+ expect(result.current[1]).toBe(true);
+
+ await act(async () => {
+ deferred.resolve("done");
+ await firstPromise;
+ });
+
+ await waitFor(() => {
+ expect(result.current[1]).toBe(false);
+ });
+ });
+
+ it("clears loading state after a rejection", async () => {
+ const deferred = createDeferred<string>();
+ const callback = vi.fn().mockReturnValue(deferred.promise);
+
+ const { result } = renderHook(() =>
+ useWatchedPromiseCallback(callback, []),
+ );
+
+ let promise!: Promise<unknown>;
+
+ act(() => {
+ promise = result.current[0]("first");
+ });
+
+ expect(result.current[1]).toBe(true);
+
+ await act(async () => {
+ deferred.reject(new Error("boom"));
+ await expect(promise).rejects.toThrow("boom");
+ });
+
+ await waitFor(() => {
+ expect(result.current[1]).toBe(false);
+ });
+ });
+
+ it("allows a new invocation after the previous promise resolves", async () => {
+ const firstDeferred = createDeferred<string>();
+ const secondDeferred = createDeferred<string>();
+ const callback = vi
+ .fn()
+ .mockReturnValueOnce(firstDeferred.promise)
+ .mockReturnValueOnce(secondDeferred.promise);
+
+ const { result } = renderHook(() =>
+ useWatchedPromiseCallback(callback, []),
+ );
+
+ let firstPromise!: Promise<unknown>;
+ let secondPromise!: Promise<unknown>;
+
+ act(() => {
+ firstPromise = result.current[0]("first");
+ });
+
+ await act(async () => {
+ firstDeferred.resolve("done");
+ await firstPromise;
+ });
+
+ await waitFor(() => {
+ expect(result.current[1]).toBe(false);
+ });
+
+ act(() => {
+ secondPromise = result.current[0]("second");
+ });
+
+ expect(callback).toHaveBeenCalledTimes(2);
+ expect(callback).toHaveBeenNthCalledWith(1, "first");
+ expect(callback).toHaveBeenNthCalledWith(2, "second");
+ expect(secondPromise).not.toBe(firstPromise);
+ expect(result.current[1]).toBe(true);
+
+ await act(async () => {
+ secondDeferred.resolve("done-again");
+ await secondPromise;
+ });
+
+ await waitFor(() => {
+ expect(result.current[1]).toBe(false);
+ });
+ });
+
+ it("clears loading state correctly in Strict Mode", async () => {
+ const deferred = createDeferred<string>();
+ const callback = vi.fn().mockReturnValue(deferred.promise);
+
+ const { result } = renderHook(
+ () => useWatchedPromiseCallback(callback, []),
+ {
+ wrapper: StrictMode,
+ },
+ );
+
+ let promise!: Promise<unknown>;
+
+ act(() => {
+ promise = result.current[0]("first");
+ });
+
+ expect(result.current[1]).toBe(true);
+
+ await act(async () => {
+ deferred.resolve("done");
+ await promise;
+ });
+
+ await waitFor(() => {
+ expect(result.current[1]).toBe(false);
+ });
+ });
+});
diff --git a/web/src/hooks/useWatchedPromiseCallback.tsx b/web/src/hooks/useWatchedPromiseCallback.tsx
new file mode 100644
index 0000000000..ee270dbd00
--- /dev/null
+++ b/web/src/hooks/useWatchedPromiseCallback.tsx
@@ -0,0 +1,58 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { DependencyList } from "react";
+
+/**
+ * Wraps a callback that returns a `Promise` with an in-flight loading state.
+ *
+ * Mirrors `useCallback` by accepting a dependency list and returning a stable
+ * callback, but also exposes whether the wrapped callback currently has an
+ * unresolved promise. The provided callback must return a `Promise`. Repeated
+ * calls while a promise is in flight reuse the same promise instead of
+ * starting duplicate work.
+ */
+export function useWatchedPromiseCallback<TArgs extends unknown[], TResult>(
+ callback: (...args: TArgs) => Promise<TResult>,
+ dependencies: DependencyList,
+) {
+ const [isLoading, setIsLoading] = useState(false);
+ const inFlightPromiseRef = useRef<Promise<TResult> | null>(null);
+ const isMountedRef = useRef(true);
+
+ useEffect(() => {
+ isMountedRef.current = true;
+
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
+
+ const watchedCallback = useCallback(
+ (...args: TArgs) => {
+ if (inFlightPromiseRef.current) {
+ return inFlightPromiseRef.current;
+ }
+
+ setIsLoading(true);
+
+ const watchedPromise = callback(...args).finally(() => {
+ if (inFlightPromiseRef.current === watchedPromise) {
+ inFlightPromiseRef.current = null;
+ }
+
+ if (isMountedRef.current) {
+ setIsLoading(false);
+ }
+ });
+
+ inFlightPromiseRef.current = watchedPromise;
+
+ return watchedPromise;
+ },
+ // react-hooks/exhaustive-deps cannot inspect forwarded dependency arrays, so callers
+ // are responsible for passing the same dependencies they would give useCallback.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ dependencies,
+ );
+
+ return [watchedCallback, isLoading] as const;
+}
diff --git a/web/src/pages/api/traces/[traceId]/download.ts b/web/src/pages/api/traces/[traceId]/download.ts
new file mode 100644
index 0000000000..a2a012dac8
--- /dev/null
+++ b/web/src/pages/api/traces/[traceId]/download.ts
@@ -0,0 +1,72 @@
+import { InvalidRequestError, UnauthorizedError } from "@langfuse/shared";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ buildTraceExport,
+ type TraceExportAccessSession,
+} from "@/src/features/traces/server/buildTraceExport";
+import { getServerAuthSession } from "@/src/server/auth";
+import { z } from "zod";
+
+const querySchema = z.object({
+ traceId: z.string().min(1),
+ projectId: z.string().min(1),
+});
+
+function getTraceExportSession(
+ session: Awaited<ReturnType<typeof getServerAuthSession>>,
+): TraceExportAccessSession {
+ if (!session) {
+ return null;
+ }
+
+ const { user } = session;
+
+ if (
+ !user ||
+ typeof user.email !== "string" ||
+ !Array.isArray(user.organizations)
+ ) {
+ throw new UnauthorizedError("Unauthorized");
+ }
+
+ return {
+ user: {
+ email: user.email,
+ admin: user.admin,
+ organizations: user.organizations,
+ },
+ };
+}
+
+const buildDownloadFilename = (traceId: string) => `trace-${traceId}.json`;
+
+export default withMiddlewares({
+ GET: async (req, res) => {
+ const session = getTraceExportSession(
+ await getServerAuthSession({ req, res }),
+ );
+
+ const result = querySchema.safeParse({
+ traceId: req.query.traceId,
+ projectId: req.query.projectId,
+ });
+
+ if (!result.success) {
+ throw new InvalidRequestError(result.error.message);
+ }
+
+ const payload = await buildTraceExport({
+ ...result.data,
+ session,
+ });
+
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
+ const downloadFilename = buildDownloadFilename(result.data.traceId);
+ res.setHeader(
+ "Content-Disposition",
+ `attachment; filename="trace-export.json"; filename*=UTF-8''${encodeURIComponent(downloadFilename)}`,
+ );
+
+ return res.status(200).send(JSON.stringify(payload, null, 2));
+ },
+});
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index 3b18bad08a..f0d9db3c1d 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -4202,6 +4202,7 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
"tool_definitions",
"tool_calls",
"tool_call_names",
+ "usage_pricing_tier_id",
"usage_pricing_tier_name",
"input",
"output",
@@ -4271,6 +4272,8 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
expect(row.trace_name).toBe("");
// --- Nullable columns (NULL when unset) ---
+ // usage_pricing_tier_id is Nullable(String) in events_core
+ expect(row.usage_pricing_tier_id).toBeNull();
// usage_pricing_tier_name is Nullable(String) in events_core
expect(row.usage_pricing_tier_name).toBeNull();
@@ -4355,6 +4358,7 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
"tool_definitions",
"tool_calls",
"tool_call_names",
+ "usage_pricing_tier_id",
"usage_pricing_tier_name",
"input",
"output",