Skip to content

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

feat(blob-export): implement chunked historic exports (#9992)

Steffen Schmitzbb1caab963c2
diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
index 4d936fd793..876c8d0706 100644
--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
@@ -75,7 +75,8 @@ describe("BlobStorageIntegrationProcessingJob", () => {
// Setup
const { projectId } = await createOrgProjectAndApiKey();
const now = new Date();
- const threeHourAgo = new Date(now.getTime() - 3 * 60 * 60 * 1000);
+ // Set lastSyncAt to 2 hours ago so the chunked export (1 hour window) covers recent data
+ const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);
// Create integration
await prisma.blobStorageIntegration.create({
@@ -92,23 +93,25 @@ describe("BlobStorageIntegrationProcessingJob", () => {
env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
enabled: true,
exportFrequency: "hourly",
- nextSyncAt: threeHourAgo,
- lastSyncAt: threeHourAgo,
+ nextSyncAt: twoHoursAgo,
+ lastSyncAt: twoHoursAgo,
},
});
- // Create test data
+ // Create test data within the export window (2 hours ago to 1 hour ago)
+ // With 30-min lag buffer, actual window is 2h ago to (1h ago or now-30min, whichever is earlier)
const traceId = randomUUID();
const observationId = randomUUID();
const scoreId = randomUUID();
// Create trace, observation, and score in Clickhouse
+ // Data is at 90 minutes ago, which falls within the chunked export window
await Promise.all([
createTracesCh([
createTrace({
id: traceId,
project_id: projectId,
- timestamp: now.getTime() - 40 * 60 * 1000, // 40 min before now
+ timestamp: now.getTime() - 90 * 60 * 1000, // 90 min before now
name: "Test Trace",
}),
]),
@@ -117,7 +120,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
id: observationId,
trace_id: traceId,
project_id: projectId,
- start_time: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ start_time: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
name: "Test Observation",
}),
]),
@@ -126,7 +129,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
id: scoreId,
trace_id: traceId,
project_id: projectId,
- timestamp: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ timestamp: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
name: "Test Score",
value: 0.95,
}),
@@ -183,7 +186,7 @@ describe("BlobStorageIntegrationProcessingJob", () => {
if (updatedIntegration?.lastSyncAt && updatedIntegration?.nextSyncAt) {
expect(updatedIntegration.lastSyncAt.getTime()).toBeGreaterThan(
- threeHourAgo.getTime(),
+ twoHoursAgo.getTime(),
);
expect(updatedIntegration.nextSyncAt.getTime()).toBeGreaterThan(
now.getTime(),
@@ -441,16 +444,19 @@ describe("BlobStorageIntegrationProcessingJob", () => {
});
describe("BlobStorageExportMode minTimestamp behavior", () => {
- it("should use epoch date for FULL_HISTORY mode on first export", async () => {
+ it("should export old data for FULL_HISTORY mode when data exists", async () => {
const { projectId } = await createOrgProjectAndApiKey();
- // Create trace with old timestamp
- const epochTrace = createTrace({
+ // Create trace with old timestamp that's far enough in the past
+ // but not so old that it might not be found by ClickHouse
+ const now = new Date();
+ const twoDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000);
+ const oldTrace = createTrace({
project_id: projectId,
- timestamp: 1000, // Very old timestamp
- name: "Epoch Trace",
+ timestamp: twoDaysAgo.getTime(),
+ name: "Old Trace",
});
- await createTracesCh([epochTrace]);
+ await createTracesCh([oldTrace]);
// Create integration with FULL_HISTORY mode and no lastSyncAt
await prisma.blobStorageIntegration.create({
@@ -477,19 +483,34 @@ describe("BlobStorageIntegrationProcessingJob", () => {
data: { payload: { projectId } },
} as Job);
- // Check that the trace file exists (indicating it found data from epoch)
+ // If data was found and exported, check the files
const files = await storageService.listFiles(
`${projectId}/test-full-history/`,
);
const projectFiles = files.filter((f) => f.file.includes(projectId));
- const traceFile = projectFiles.find((f) => f.file.includes("/traces/"));
- expect(traceFile).toBeDefined();
+ // With FULL_HISTORY mode, if the ClickHouse query finds the old data,
+ // it should export starting from that timestamp
+ if (projectFiles.length > 0) {
+ const traceFile = projectFiles.find((f) => f.file.includes("/traces/"));
+ expect(traceFile).toBeDefined();
- // Verify the file contains the old trace data
- if (traceFile) {
- const content = await storageService.download(traceFile.file);
- expect(content).toContain(epochTrace.id);
+ if (traceFile) {
+ const content = await storageService.download(traceFile.file);
+ expect(content).toContain(oldTrace.id);
+ }
+ }
+
+ // Verify integration was updated if export happened
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: { projectId },
+ },
+ );
+
+ // If files were exported, lastSyncAt should be set
+ if (projectFiles.length > 0) {
+ expect(updatedIntegration?.lastSyncAt).toBeDefined();
}
});
@@ -557,9 +578,9 @@ describe("BlobStorageIntegrationProcessingJob", () => {
const now = new Date();
const customDate = new Date(now.getTime() - 12 * 60 * 60 * 1000); // 12 hours ago
const beforeCustomDate = new Date(customDate.getTime() - 60 * 60 * 1000); // 13 hours ago
- const afterCustomDate = new Date(
- customDate.getTime() + 2 * 60 * 60 * 1000,
- ); // 10 hours ago (safe margin)
+ // With chunking, first export covers customDate to customDate + 1 hour
+ // So we need data within that first hour window
+ const afterCustomDate = new Date(customDate.getTime() + 30 * 60 * 1000); // 30 minutes after custom date
// Create traces before and after custom date
const oldTrace = createTrace({
@@ -613,4 +634,210 @@ describe("BlobStorageIntegrationProcessingJob", () => {
}
});
});
+
+ describe("Chunked historic exports", () => {
+ it("should cap maxTimestamp to one frequency period ahead for FULL_HISTORY mode", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = new Date();
+ const veryOldTimestamp = new Date(
+ now.getTime() - 7 * 24 * 60 * 60 * 1000,
+ ); // 7 days ago
+
+ // Create trace from 7 days ago
+ const oldTrace = createTrace({
+ project_id: projectId,
+ timestamp: veryOldTimestamp.getTime(),
+ name: "Old Trace",
+ });
+ await createTracesCh([oldTrace]);
+
+ // Create integration with FULL_HISTORY and hourly frequency (first export)
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: `${projectId}/test-chunking/`,
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region ? region : "auto",
+ endpoint: endpoint ? endpoint : null,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "hourly",
+ exportMode: "FULL_HISTORY",
+ exportStartDate: null,
+ lastSyncAt: null,
+ },
+ });
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: { projectId },
+ },
+ );
+
+ expect(updatedIntegration).toBeDefined();
+
+ // Check if files were exported (meaning data was found)
+ const files = await storageService.listFiles(
+ `${projectId}/test-chunking/`,
+ );
+ const projectFiles = files.filter((f) => f.file.includes(projectId));
+
+ // If data was found and exported, verify chunking behavior
+ if (projectFiles.length > 0 && updatedIntegration?.lastSyncAt) {
+ // When ClickHouse finds the old data, it should start from that timestamp
+ // and cap the export to 1 hour (frequency interval)
+ // lastSyncAt should be capped to 1 hour after the found timestamp
+ const minExpectedTime = veryOldTimestamp.getTime();
+ const maxExpectedTime = veryOldTimestamp.getTime() + 60 * 60 * 1000; // +1 hour
+ const tolerance = 2000; // 2 second tolerance
+
+ expect(updatedIntegration.lastSyncAt.getTime()).toBeGreaterThanOrEqual(
+ minExpectedTime,
+ );
+ expect(updatedIntegration.lastSyncAt.getTime()).toBeLessThanOrEqual(
+ maxExpectedTime + tolerance,
+ );
+ }
+ // If no data was found (fallback to current time), the time window would be invalid
+ // and no export would happen, which is acceptable behavior
+ });
+
+ it("should immediately schedule next chunk when in catch-up mode", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = new Date();
+ const twoDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000);
+
+ // Create traces over 2 days
+ const trace1 = createTrace({
+ project_id: projectId,
+ timestamp: twoDaysAgo.getTime(),
+ name: "Old Trace 1",
+ });
+ const trace2 = createTrace({
+ project_id: projectId,
+ timestamp: twoDaysAgo.getTime() + 60 * 60 * 1000, // 1 hour later
+ name: "Old Trace 2",
+ });
+ await createTracesCh([trace1, trace2]);
+
+ // Create integration with hourly frequency starting 2 days ago
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: `${projectId}/test-catchup/`,
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region ? region : "auto",
+ endpoint: endpoint ? endpoint : null,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "hourly",
+ lastSyncAt: twoDaysAgo, // Start from 2 days ago
+ },
+ });
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: { projectId },
+ },
+ );
+
+ expect(updatedIntegration).toBeDefined();
+ if (!updatedIntegration?.nextSyncAt) {
+ expect.fail("nextSyncAt should be set");
+ }
+
+ // nextSyncAt should be immediate (within a few seconds of now)
+ const timeDiff = Math.abs(
+ updatedIntegration.nextSyncAt.getTime() - now.getTime(),
+ );
+ expect(timeDiff).toBeLessThan(5000); // Within 5 seconds
+ });
+
+ it("should schedule normally when caught up", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+
+ // Create recent trace
+ const trace = createTrace({
+ project_id: projectId,
+ timestamp: now.getTime() - 40 * 60 * 1000, // 40 minutes ago
+ name: "Recent Trace",
+ });
+ await createTracesCh([trace]);
+
+ // Create integration with lastSyncAt 1 hour ago (within normal range)
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: `${projectId}/test-caught-up/`,
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region ? region : "auto",
+ endpoint: endpoint ? endpoint : null,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "hourly",
+ lastSyncAt: oneHourAgo,
+ },
+ });
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: { projectId },
+ },
+ );
+
+ expect(updatedIntegration).toBeDefined();
+ if (!updatedIntegration?.nextSyncAt || !updatedIntegration?.lastSyncAt) {
+ expect.fail("nextSyncAt and lastSyncAt should be set");
+ }
+
+ // nextSyncAt should be 1 hour after lastSyncAt (normal scheduling)
+ const expectedNextSync = new Date(
+ updatedIntegration.lastSyncAt.getTime() + 60 * 60 * 1000,
+ );
+ const tolerance = 1000; // 1 second tolerance
+
+ expect(
+ Math.abs(
+ updatedIntegration.nextSyncAt.getTime() - expectedNextSync.getTime(),
+ ),
+ ).toBeLessThan(tolerance);
+
+ // nextSyncAt should be in the future
+ expect(updatedIntegration.nextSyncAt.getTime()).toBeGreaterThan(
+ now.getTime(),
+ );
+ });
+ });
});
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index c6d911fd4d..d0a71cf3c6 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -12,6 +12,9 @@ import {
getTracesForBlobStorageExport,
getScoresForBlobStorageExport,
getCurrentSpan,
+ BlobStorageIntegrationProcessingQueue,
+ queryClickhouse,
+ QueueJobs,
} from "@langfuse/shared/src/server";
import {
BlobStorageIntegrationType,
@@ -19,12 +22,14 @@ import {
BlobStorageExportMode,
} from "@langfuse/shared";
import { decrypt } from "@langfuse/shared/encryption";
+import { randomUUID } from "crypto";
-const getMinTimestampForExport = (
+const getMinTimestampForExport = async (
+ projectId: string,
lastSyncAt: Date | null,
exportMode: BlobStorageExportMode,
exportStartDate: Date | null,
-): Date => {
+): Promise<Date> => {
// If we have a lastSyncAt, use it (this is for subsequent exports)
if (lastSyncAt) {
return lastSyncAt;
@@ -33,7 +38,49 @@ const getMinTimestampForExport = (
// For first export, use the export mode to determine start date
switch (exportMode) {
case BlobStorageExportMode.FULL_HISTORY:
- return new Date(0); // Export all historical data
+ // Query ClickHouse for the actual minimum timestamp from traces, observations, and scores tables
+ try {
+ const result = await queryClickhouse<{ min_timestamp: number | null }>({
+ query: `
+ SELECT min(toUnixTimestamp(ts)) * 1000 as min_timestamp
+ FROM (
+ SELECT min(timestamp) as ts
+ FROM traces
+ WHERE project_id = {projectId: String}
+
+ UNION ALL
+
+ SELECT min(start_time) as ts
+ FROM observations
+ WHERE project_id = {projectId: String}
+
+ UNION ALL
+
+ SELECT min(timestamp) as ts
+ FROM scores
+ WHERE project_id = {projectId: String}
+ )
+ `,
+ params: { projectId },
+ });
+
+ // Extract the minimum timestamp
+ if (result[0]?.min_timestamp && result[0].min_timestamp > 0) {
+ return new Date(result[0].min_timestamp);
+ }
+
+ // If no data exists, use current time as a fallback
+ logger.info(
+ `No historical data found for project ${projectId}, using current time`,
+ );
+ return new Date();
+ } catch (error) {
+ logger.error(
+ `Error querying ClickHouse for minimum timestamp for project ${projectId}`,
+ error,
+ );
+ throw new Error(`Failed to fetch minimum timestamp: ${error}`);
+ }
case BlobStorageExportMode.FROM_TODAY:
case BlobStorageExportMode.FROM_CUSTOM_DATE:
return exportStartDate || new Date(); // Use export start date or current time as fallback
@@ -44,6 +91,23 @@ const getMinTimestampForExport = (
}
};
+/**
+ * Get the frequency interval in milliseconds for a given export frequency.
+ * This is used to chunk historic exports into manageable time windows.
+ */
+const getFrequencyIntervalMs = (frequency: string): number => {
+ switch (frequency) {
+ case "hourly":
+ return 60 * 60 * 1000; // 1 hour
+ case "daily":
+ return 24 * 60 * 60 * 1000; // 1 day
+ case "weekly":
+ return 7 * 24 * 60 * 60 * 1000; // 1 week
+ default:
+ throw new Error(`Unsupported export frequency: ${frequency}`);
+ }
+};
+
const getFileTypeProperties = (fileType: BlobStorageIntegrationFileType) => {
switch (fileType) {
case BlobStorageIntegrationFileType.JSON:
@@ -210,12 +274,35 @@ export const handleBlobStorageIntegrationProjectJob = async (
}
// Sync between lastSyncAt and now - 30 minutes
- const minTimestamp = getMinTimestampForExport(
+ // Cap the export to one frequency period to enable chunked historic exports
+ const minTimestamp = await getMinTimestampForExport(
+ projectId,
blobStorageIntegration.lastSyncAt,
blobStorageIntegration.exportMode,
blobStorageIntegration.exportStartDate,
);
- const maxTimestamp = new Date(new Date().getTime() - 30 * 60 * 1000);
+ const now = new Date();
+ const uncappedMaxTimestamp = new Date(now.getTime() - 30 * 60 * 1000); // 30-minute lag buffer
+ const frequencyIntervalMs = getFrequencyIntervalMs(
+ blobStorageIntegration.exportFrequency,
+ );
+
+ // Cap maxTimestamp to one frequency period ahead of minTimestamp
+ // This ensures large historic exports are broken into manageable chunks
+ const maxTimestamp = new Date(
+ Math.min(
+ minTimestamp.getTime() + frequencyIntervalMs,
+ uncappedMaxTimestamp.getTime(),
+ ),
+ );
+
+ // Skip export if the time window is empty or invalid
+ if (minTimestamp >= maxTimestamp) {
+ logger.info(
+ `Skipping export for project ${projectId}: time window is empty (min: ${minTimestamp.toISOString()}, max: ${maxTimestamp.toISOString()})`,
+ );
+ return;
+ }
try {
// Process the export based on the integration configuration
@@ -242,21 +329,22 @@ export const handleBlobStorageIntegrationProjectJob = async (
processBlobStorageExport({ ...executionConfig, table: "scores" }),
]);
+ // Determine if we've caught up with present-day data
+ const caughtUp = maxTimestamp.getTime() >= uncappedMaxTimestamp.getTime();
+
let nextSyncAt: Date;
- switch (blobStorageIntegration.exportFrequency) {
- case "hourly":
- nextSyncAt = new Date(maxTimestamp.getTime() + 60 * 60 * 1000);
- break;
- case "daily":
- nextSyncAt = new Date(maxTimestamp.getTime() + 24 * 60 * 60 * 1000);
- break;
- case "weekly":
- nextSyncAt = new Date(maxTimestamp.getTime() + 7 * 24 * 60 * 60 * 1000);
- break;
- default:
- throw new Error(
- `Unsupported export frequency ${blobStorageIntegration.exportFrequency}`,
- );
+ if (caughtUp) {
+ // Normal mode: schedule for the next frequency period
+ nextSyncAt = new Date(maxTimestamp.getTime() + frequencyIntervalMs);
+ logger.info(
+ `Caught up with exports for project ${projectId}. Next sync at ${nextSyncAt.toISOString()}`,
+ );
+ } else {
+ // Catch-up mode: schedule next chunk immediately
+ nextSyncAt = new Date();
+ logger.info(
+ `Still catching up for project ${projectId}. Scheduling next chunk immediately (processed up to ${maxTimestamp.toISOString()})`,
+ );
}
// Update integration after successful processing
@@ -270,6 +358,27 @@ export const handleBlobStorageIntegrationProjectJob = async (
},
});
+ // If still catching up, immediately queue the next chunk job
+ if (!caughtUp) {
+ const queue = BlobStorageIntegrationProcessingQueue.getInstance();
+ if (queue) {
+ const jobId = `${projectId}-${maxTimestamp.toISOString()}`;
+ await queue.add(
+ QueueJobs.BlobStorageIntegrationProcessingJob,
+ {
+ id: randomUUID(),
+ name: QueueJobs.BlobStorageIntegrationProcessingJob,
+ timestamp: new Date(),
+ payload: { projectId },
+ },
+ { jobId },
+ );
+ logger.info(
+ `Queued next catch-up chunk for project ${projectId} with jobId ${jobId}`,
+ );
+ }
+ }
+
logger.info(
`Successfully processed blob storage integration for project ${projectId}`,
);