Skip to content

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

feat(blob-export): add more fields to v3 and v4 blob storage exports (#12840)

Valery Meleshkin942db0fc4e62
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 f95962f635..6b065580a8 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
@@ -101,6 +101,10 @@ const EVENTS_FIELDS = {
toolCalls: 'e.tool_calls as "tool_calls"',
toolCallNames: 'e.tool_call_names as "tool_call_names"',
+ // Pricing tier
+ usagePricingTierName:
+ 'e.usage_pricing_tier_name as "usage_pricing_tier_name"',
+
// I/O & metadata fields
input: "e.input",
output: "e.output",
@@ -278,6 +282,14 @@ const FIELD_SETS = {
"release",
"traceName",
"parentObservationId",
+ "bookmarked",
+ "public",
+ "createdAt",
+ "updatedAt",
+ "toolDefinitions",
+ "toolCalls",
+ "toolCallNames",
+ "usagePricingTierName",
],
eval: [
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 3b86b2e727..cb35322e49 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -1803,7 +1803,18 @@ export const getObservationsForBlobStorageExport = function (
cost_details,
completion_start_time,
prompt_name,
- prompt_version
+ prompt_version,
+ total_cost,
+ if(isNull(end_time), NULL, date_diff('millisecond', start_time, end_time) / 1000) as latency,
+ if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time) / 1000) as time_to_first_token,
+ internal_model_id as model_id,
+ created_at,
+ updated_at,
+ prompt_id,
+ tool_calls,
+ tool_call_names,
+ tool_definitions,
+ usage_pricing_tier_name
FROM observations FINAL
WHERE project_id = {projectId: String}
AND start_time >= {minTimestamp: DateTime64(3)}
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index 2aa540154f..dead438fa0 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -19,9 +19,45 @@ import {
applyInputOutputRendering,
} from "../utils/rendering";
import { logger } from "../logger";
+import { prisma } from "../../db";
import type { Model, Price } from "@prisma/client";
-type ModelWithPrice = Model & { Price: Price[] };
+export type ModelWithPrice = Model & { Price: Price[] };
+
+/**
+ * Creates a model cache that fetches models from the database on demand and stores them in memory.
+ * Only queries the database if a model ID is not already in the cache.
+ */
+export const createModelCache = (projectId: string) => {
+ const modelCache = new Map<string, ModelWithPrice | null>();
+
+ const getModel = async (
+ internalModelId: string | null | undefined,
+ ): Promise<ModelWithPrice | null> => {
+ if (!internalModelId) return null;
+
+ if (modelCache.has(internalModelId)) {
+ return modelCache.get(internalModelId) ?? null;
+ }
+
+ const model = await prisma.model.findFirst({
+ where: {
+ id: internalModelId,
+ OR: [{ projectId }, { projectId: null }],
+ },
+ include: {
+ Price: true,
+ },
+ });
+
+ modelCache.set(internalModelId, model);
+
+ logger.debug(`Model ${internalModelId} fetched from database`);
+ return model;
+ };
+
+ return { getModel };
+};
/**
* Converts a Record<string, number> to ensure all values are numbers.
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index abe04539fb..6fe487921d 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -2000,7 +2000,9 @@ export const getScoresForBlobStorageExport = function (
source,
comment,
data_type,
- string_value
+ string_value,
+ created_at,
+ updated_at
FROM scores FINAL
WHERE project_id = {projectId: String}
AND timestamp >= {minTimestamp: DateTime64(3)}
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index a812a66e00..a2e038ae32 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -1372,7 +1372,9 @@ export const getTracesForBlobStorageExport = function (
bookmarked as bookmarked,
tags,
input as input,
- output as output
+ output as output,
+ created_at,
+ updated_at
FROM ${traceTable} FINAL
WHERE project_id = {projectId: String}
AND timestamp >= {minTimestamp: DateTime64(3)}
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index e3207eec83..99d3ef534c 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -4003,6 +4003,44 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
expect(rows[0].type).toBe("GENERATION");
});
+ it("should export bookmarked, public, created_at, and updated_at fields", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = Date.now();
+ const traceId = randomUUID();
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-fields-event",
+ start_time: now * 1000,
+ bookmarked: true,
+ public: true,
+ });
+
+ await createEventsCh([event]);
+
+ const stream = getEventsForBlobStorageExport(
+ projectId,
+ new Date(now - 60 * 60 * 1000),
+ new Date(now + 60 * 60 * 1000),
+ );
+
+ const rows: Record<string, unknown>[] = [];
+ for await (const row of stream) {
+ rows.push(row);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].bookmarked).toBe(true);
+ expect(rows[0].public).toBe(true);
+ expect(rows[0].created_at).toBeDefined();
+ expect(rows[0].updated_at).toBeDefined();
+ expect(rows[0].tool_calls).toBeDefined();
+ expect(rows[0].tool_definitions).toBeDefined();
+ expect(rows[0].tool_call_names).toBeDefined();
+ });
+
it("should filter events by time range", async () => {
const { projectId } = await createOrgProjectAndApiKey();
const now = Date.now();
diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
index 686ba84dc4..9d99c6d635 100644
--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
@@ -153,6 +153,37 @@ describe("BlobStorageIntegrationProcessingJob", () => {
const traceId = randomUUID();
const observationId = randomUUID();
const scoreId = randomUUID();
+ const modelId = randomUUID();
+
+ const dataTime = now.getTime() - 90 * 60 * 1000; // 90 minutes before now
+
+ // Create a Model + PricingTier + Prices in Postgres for model enrichment
+ await prisma.model.create({
+ data: {
+ id: modelId,
+ projectId,
+ modelName: "gpt-4-test",
+ matchPattern: "gpt-4-test",
+ unit: "TOKENS",
+ pricingTiers: {
+ create: {
+ name: "Standard",
+ isDefault: true,
+ conditions: [],
+ priority: 0,
+ prices: {
+ createMany: {
+ data: [
+ { modelId, usageType: "input", price: "0.03" },
+ { modelId, usageType: "output", price: "0.06" },
+ { modelId, usageType: "total", price: "0.09" },
+ ],
+ },
+ },
+ },
+ },
+ },
+ });
// Create event data for events table export
const event = createEvent({
@@ -160,7 +191,11 @@ describe("BlobStorageIntegrationProcessingJob", () => {
trace_id: traceId,
type: "GENERATION",
name: "Test Event",
- start_time: (now.getTime() - 90 * 60 * 1000) * 1000, // 90 minutes before now (microseconds)
+ start_time: dataTime * 1000, // microseconds
+ end_time: (dataTime + 5000) * 1000, // 5s later (microseconds)
+ bookmarked: true,
+ public: true,
+ model_id: modelId,
});
// Create trace, observation, score, and event in Clickhouse
@@ -170,7 +205,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
createTrace({
id: traceId,
project_id: projectId,
- timestamp: now.getTime() - 90 * 60 * 1000, // 90 min before now
+ timestamp: dataTime,
name: "Test Trace",
}),
]),
@@ -179,7 +214,12 @@ describe("BlobStorageIntegrationProcessingJob", () => {
id: observationId,
trace_id: traceId,
project_id: projectId,
- start_time: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
+ start_time: dataTime,
+ end_time: dataTime + 5000, // 5s later
+ completion_start_time: dataTime + 1000, // 1s later
+ total_cost: 42.5,
+ usage_details: { input: 100, output: 200, total: 300 },
+ internal_model_id: modelId,
name: "Test Observation",
}),
]),
@@ -188,7 +228,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
id: scoreId,
trace_id: traceId,
project_id: projectId,
- timestamp: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
+ timestamp: dataTime,
name: "Test Score",
value: 0.95,
}),
@@ -196,7 +236,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
id: sessionScoreId,
session_id: sessionId,
project_id: projectId,
- timestamp: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
+ timestamp: dataTime,
name: "Test Session Score",
value: 0.8,
}),
@@ -204,7 +244,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
id: datasetRunScoreId,
dataset_run_id: datasetRunId,
project_id: projectId,
- timestamp: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
+ timestamp: dataTime,
name: "Test Dataset Run Score",
value: 0.7,
}),
@@ -244,12 +284,33 @@ describe("BlobStorageIntegrationProcessingJob", () => {
const content = await s3StorageService.download(traceFile.file);
expect(content).toContain(traceId);
expect(content).toContain("Test Trace");
+ // Verify new fields: created_at, updated_at
+ expect(content).toContain("created_at");
+ expect(content).toContain("updated_at");
}
if (observationFile) {
const content = await s3StorageService.download(observationFile.file);
expect(content).toContain(observationId);
expect(content).toContain("Test Observation");
+ // Verify new fields: total_cost, latency, time_to_first_token
+ expect(content).toContain("total_cost");
+ expect(content).toContain("latency");
+ expect(content).toContain("time_to_first_token");
+ // Verify usage_details map contains actual token counts (CSV escapes " as "")
+ expect(content).toContain('""input"":100');
+ expect(content).toContain('""output"":200');
+ // Verify model pricing enrichment
+ expect(content).toContain("input_price");
+ expect(content).toContain("output_price");
+ expect(content).toContain("total_price");
+ expect(content).toContain("0.03");
+ expect(content).toContain("0.06");
+ // Verify newly added native fields
+ expect(content).toContain("prompt_id");
+ expect(content).toContain("tool_calls");
+ expect(content).toContain("tool_definitions");
+ expect(content).toContain("usage_pricing_tier_name");
}
if (scoreFile) {
@@ -267,12 +328,33 @@ describe("BlobStorageIntegrationProcessingJob", () => {
expect(content).toContain(datasetRunId);
expect(content).toContain("Test Dataset Run Score");
expect(content).toContain("0.7");
+ // Verify new fields: created_at, updated_at
+ expect(content).toContain("created_at");
+ expect(content).toContain("updated_at");
}
if (eventFile) {
const content = await s3StorageService.download(eventFile.file);
expect(content).toContain(event.span_id);
expect(content).toContain("Test Event");
+ // Verify new fields: bookmarked, public, created_at, updated_at
+ expect(content).toContain("bookmarked");
+ expect(content).toContain("public");
+ expect(content).toContain("created_at");
+ expect(content).toContain("updated_at");
+ // Verify usage_details map contains actual token counts (CSV escapes " as "")
+ expect(content).toContain('""input"":1234');
+ expect(content).toContain('""output"":5678');
+ // Verify model pricing enrichment with actual values
+ expect(content).toContain("input_price");
+ expect(content).toContain("output_price");
+ expect(content).toContain("total_price");
+ expect(content).toContain("0.03");
+ expect(content).toContain("0.06");
+ // Verify newly added native fields
+ expect(content).toContain("tool_calls");
+ expect(content).toContain("tool_definitions");
+ expect(content).toContain("usage_pricing_tier_name");
}
// Check integration lastSyncAt and nextSyncAt are updated
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 48b65b698e..97432cd14c 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -19,6 +19,8 @@ import {
QueueJobs,
sendBlobStorageExportFailedEmail,
getProjectAdminEmails,
+ enrichObservationWithModelData,
+ createModelCache,
} from "@langfuse/shared/src/server";
import {
BlobStorageIntegrationType,
@@ -29,6 +31,38 @@ import { decrypt } from "@langfuse/shared/encryption";
import { randomUUID } from "crypto";
import { env } from "../../env";
+async function* enrichObservationStream(
+ stream: AsyncGenerator<Record<string, unknown>>,
+ projectId: string,
+ modelIdField: string,
+ convertLatencyToSeconds: boolean,
+): AsyncGenerator<Record<string, unknown>> {
+ const { getModel } = createModelCache(projectId);
+
+ for await (const row of stream) {
+ const modelId = row[modelIdField] as string | null | undefined;
+ const model = await getModel(modelId);
+ const pricing = enrichObservationWithModelData(model);
+
+ const enriched: Record<string, unknown> = {
+ ...row,
+ model_id: pricing.modelId ?? modelId ?? null,
+ input_price: pricing.inputPrice,
+ output_price: pricing.outputPrice,
+ total_price: pricing.totalPrice,
+ };
+
+ if (convertLatencyToSeconds) {
+ const latency = row.latency as number | null;
+ const ttft = row.time_to_first_token as number | null;
+ enriched.latency = latency != null ? latency / 1000 : null;
+ enriched.time_to_first_token = ttft != null ? ttft / 1000 : null;
+ }
+
+ yield enriched;
+ }
+}
+
const getMinTimestampForExport = async (
projectId: string,
lastSyncAt: Date | null,
@@ -162,6 +196,7 @@ const processBlobStorageExport = async (config: {
table: "traces" | "observations" | "scores" | "observations_v2"; // observations_v2 is the events table
fileType: BlobStorageIntegrationFileType;
compressed: boolean;
+ convertV4LatencyToSeconds: boolean;
}) => {
logger.info(
`[BLOB INTEGRATION] Processing ${config.table} export for project ${config.projectId}`,
@@ -209,10 +244,15 @@ const processBlobStorageExport = async (config: {
);
break;
case "observations":
- dataStream = getObservationsForBlobStorageExport(
+ dataStream = enrichObservationStream(
+ getObservationsForBlobStorageExport(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ ),
config.projectId,
- config.minTimestamp,
- config.maxTimestamp,
+ "model_id",
+ false, // v3 query already returns latency in seconds
);
break;
case "scores":
@@ -223,10 +263,15 @@ const processBlobStorageExport = async (config: {
);
break;
case "observations_v2": // observations_v2 is the events table
- dataStream = getEventsForBlobStorageExport(
+ dataStream = enrichObservationStream(
+ getEventsForBlobStorageExport(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ ),
config.projectId,
- config.minTimestamp,
- config.maxTimestamp,
+ "model_id",
+ config.convertV4LatencyToSeconds,
);
break;
default:
@@ -349,6 +394,13 @@ export const handleBlobStorageIntegrationProjectJob = async (
try {
// Process the export based on the integration configuration
+ // Convert v4 (events table) latency/time_to_first_token from ms to seconds
+ // for integrations created on or after 2026-04-01. Before this date, v4 blob
+ // export returned these fields in milliseconds. We preserve that behavior for
+ // existing integrations to avoid silently breaking their pipelines.
+ const convertV4LatencyToSeconds =
+ blobStorageIntegration.createdAt >= new Date("2026-04-01T00:00:00Z");
+
const executionConfig = {
projectId,
minTimestamp,
@@ -365,6 +417,7 @@ export const handleBlobStorageIntegrationProjectJob = async (
type: blobStorageIntegration.type,
fileType: blobStorageIntegration.fileType,
compressed: blobStorageIntegration.compressed,
+ convertV4LatencyToSeconds,
};
// Check if this project should only export traces (legacy behavior via env var)
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index c86ac33aee..8d1d7883e8 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -10,18 +10,17 @@ import {
import {
getDistinctScoreNames,
queryClickhouseStream,
- logger,
ObservationRecordReadType,
StringFilter,
FilterList,
createFilterFromFilterState,
observationsTableUiColumnDefinitions,
enrichObservationWithModelData,
+ createModelCache,
clickhouseSearchCondition,
convertObservation,
shouldSkipObservationsFinal,
} from "@langfuse/shared/src/server";
-import { prisma } from "@langfuse/shared/src/db";
import { Readable } from "stream";
import { env } from "../../env";
import {
@@ -29,54 +28,10 @@ import {
prepareScoresForOutput,
} from "./getDatabaseReadStream";
import { fetchCommentsForExport } from "./fetchCommentsForExport";
-import type { Model, Price } from "@prisma/client";
const DEFAULT_BATCH_SIZE = 1000;
const REDUCED_BATCH_SIZE = 200; // Smaller batch for JSON/JSONL which hold parsed objects in memory
-type ModelWithPrice = Model & { Price: Price[] };
-
-/**
- * Creates a model cache that fetches models from the database on demand and stores them in memory.
- * Only queries the database if a model ID is not already in the cache.
- *
- * @param projectId - The project ID to filter models by
- * @returns Object with getModel function to retrieve models by ID
- */
-const createModelCache = (projectId: string) => {
- const modelCache = new Map<string, ModelWithPrice | null>();
-
- const getModel = async (
- internalModelId: string | null | undefined,
- ): Promise<ModelWithPrice | null> => {
- if (!internalModelId) return null;
-
- // Check if model is already in cache
- if (modelCache.has(internalModelId)) {
- return modelCache.get(internalModelId) ?? null;
- }
-
- // Fetch model from database
- const model = await prisma.model.findFirst({
- where: {
- id: internalModelId,
- OR: [{ projectId }, { projectId: null }],
- },
- include: {
- Price: true,
- },
- });
-
- // Store in cache (even if null to avoid repeated queries)
- modelCache.set(internalModelId, model);
-
- logger.debug(`Model ${internalModelId} fetched from database`);
- return model;
- };
-
- return { getModel };
-};
-
export const getObservationStream = async (props: {
projectId: string;
cutoffCreatedAt: Date;