🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: migrate event_log table to new blob storage table (#6534)
Max Deichmann2a871d1e7546
diff --git a/packages/shared/clickhouse/migrations/clustered/0011_add_blob_storage_file_log.down.sql b/packages/shared/clickhouse/migrations/clustered/0011_add_blob_storage_file_log.down.sqlnew file mode 100644index 0000000000..29a74f1c78--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0011_add_blob_storage_file_log.down.sql@@ -0,0 +1 @@+DROP TABLE blob_storage_file_log ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/clustered/0011_add_blob_storage_file_log.up.sql b/packages/shared/clickhouse/migrations/clustered/0011_add_blob_storage_file_log.up.sqlnew file mode 100644index 0000000000..664281ad4c--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0011_add_blob_storage_file_log.up.sql@@ -0,0 +1,21 @@+CREATE TABLE blob_storage_file_log ON CLUSTER default (+ `id` String,+ `project_id` String,+ `entity_type` String,+ `entity_id` String,+ `event_id` String,++ `bucket_name` String,+ `bucket_path` String,++ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now(),+ event_ts DateTime64(3),+ is_deleted UInt8,+) ENGINE = ReplicatedReplacingMergeTree(event_ts, is_deleted)+ ORDER BY (+ project_id,+ entity_type,+ entity_id,+ event_id+ );diff --git a/packages/shared/clickhouse/migrations/unclustered/0011_add_blob_storage_file_log.down.sql b/packages/shared/clickhouse/migrations/unclustered/0011_add_blob_storage_file_log.down.sqlnew file mode 100644index 0000000000..a23949b45c--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0011_add_blob_storage_file_log.down.sql@@ -0,0 +1 @@+DROP TABLE blob_storage_file_log;diff --git a/packages/shared/clickhouse/migrations/unclustered/0011_add_blob_storage_file_log.up.sql b/packages/shared/clickhouse/migrations/unclustered/0011_add_blob_storage_file_log.up.sqlnew file mode 100644index 0000000000..70150bef29--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0011_add_blob_storage_file_log.up.sql@@ -0,0 +1,22 @@+CREATE TABLE blob_storage_file_log+(+ `id` String,+ `project_id` String,+ `entity_type` String,+ `entity_id` String,+ `event_id` String,++ `bucket_name` String,+ `bucket_path` String,++ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now(),+ event_ts DateTime64(3),+ is_deleted UInt8,+) ENGINE = ReplacingMergeTree(event_ts, is_deleted)+ ORDER BY (+ project_id,+ entity_type,+ entity_id,+ event_id+ );diff --git a/packages/shared/prisma/migrations/20250517173700_add_event_log_migration_background_migration.sql/migration.sql b/packages/shared/prisma/migrations/20250517173700_add_event_log_migration_background_migration.sql/migration.sqlnew file mode 100644index 0000000000..aec65432da--- /dev/null+++ b/packages/shared/prisma/migrations/20250517173700_add_event_log_migration_background_migration.sql/migration.sql@@ -0,0 +1,2 @@+INSERT INTO background_migrations (id, name, script, args)+VALUES ('c19b91d9-f9a2-468b-8209-95578f970c5b', '20250417_1737_migrate_event_log_to_blob_storage', 'migrateEventLogToBlobStorageRefTable', '{}');diff --git a/packages/shared/src/server/repositories/eventLog.ts b/packages/shared/src/server/repositories/blobStorageLog.tssimilarity index 68%rename from packages/shared/src/server/repositories/eventLog.tsrename to packages/shared/src/server/repositories/blobStorageLog.tsindex 6a4b7f8823..f28bbb24be 100644--- a/packages/shared/src/server/repositories/eventLog.ts+++ b/packages/shared/src/server/repositories/blobStorageLog.ts@@ -1,19 +1,20 @@import {commandClickhouse,+ parseClickhouseUTCDateTimeFormat,queryClickhouse,queryClickhouseStream,} from "./clickhouse";import { EventLogRecordReadType } from "./definitions";import { convertDateToClickhouseDateTime } from "../clickhouse/client";-export const getEventLogByProjectAndEntityId = async (+export const getBlobStorageByProjectAndEntityId = async (projectId: string,entityType: string,entityId: string,): Promise<EventLogRecordReadType[]> => {const query = `select *- from event_log+ from blob_storage_file_logwhere project_id = {projectId: String}and entity_type = {entityType: String}and entity_id = {entityId: String}@@ -34,12 +35,12 @@ export const getEventLogByProjectAndEntityId = async (});};-export const getEventLogByProjectId = (+export const getBlobStorageByProjectId = (projectId: string,): AsyncGenerator<EventLogRecordReadType> => {const query = `select *- from event_log+ from blob_storage_file_logwhere project_id = {projectId: String}`;@@ -56,13 +57,13 @@ export const getEventLogByProjectId = (});};-export const getEventLogByProjectIdBeforeDate = (+export const getBlobStorageByProjectIdBeforeDate = (projectId: string,beforeDate: Date,): AsyncGenerator<EventLogRecordReadType> => {const query = `select *- from event_log+ from blob_storage_file_logwhere project_id = {projectId: String}and created_at <= {beforeDate: DateTime64(3)}`;@@ -81,14 +82,14 @@ export const getEventLogByProjectIdBeforeDate = (});};-export const getEventLogByProjectIdAndEntityIds = (+export const getBlobStorageByProjectIdAndEntityIds = (projectId: string,entityType: "observation" | "trace" | "score",entityIds: string[],): AsyncGenerator<EventLogRecordReadType> => {const query = `select *- from event_log+ from blob_storage_file_logwhere project_id = {projectId: String}and entity_type = {entityType: String}and entity_id in ({entityIds: Array(String)})@@ -112,7 +113,7 @@ export const getEventLogByProjectIdAndEntityIds = (});};-export const getEventLogByProjectIdAndTraceIds = (+export const getBlobStorageByProjectIdAndTraceIds = (projectId: string,traceIds: string[],): AsyncGenerator<EventLogRecordReadType> => {@@ -155,7 +156,7 @@ export const getEventLogByProjectIdAndTraceIds = (-- We use a semi join because we only use the 'filtered_events' as a filter.-- There is no need to build the cartesian product (i.e. the combination) between the event log and the events.select el.*- from event_log el+ from blob_storage_file_log elleft semi join filtered_events feon el.project_id = fe.project_id and el.entity_id = fe.entity_id and el.entity_type = fe.entity_typewhere el.project_id = {projectId: String}@@ -183,12 +184,12 @@ export const getEventLogByProjectIdAndTraceIds = (* @param projectId - Project ID* @param ids - ID record of the event log table to be deleted*/-export const deleteEventLogByProjectIdAndIds = async (+export const deleteBlobStorageByProjectIdAndIds = async (projectId: string,ids: string[],): Promise<void> => {const query = `- delete from event_log+ delete from blob_storage_file_logwhere project_id = {projectId: String}and id in ({ids: Array(String)});`;@@ -210,11 +211,11 @@ export const deleteEventLogByProjectIdAndIds = async (});};-export const deleteEventLogByProjectId = async (+export const deleteBlobStorageByProjectId = async (projectId: string,): Promise<void> => {const query = `- DELETE FROM event_log+ DELETE FROM blob_storage_file_logWHERE project_id = {projectId: String};`;await commandClickhouse({@@ -233,12 +234,12 @@ export const deleteEventLogByProjectId = async (});};-export const deleteEventLogByProjectIdBeforeDate = async (+export const deleteBlobStorageByProjectIdBeforeDate = async (projectId: string,beforeDate: Date,): Promise<void> => {const query = `- DELETE FROM event_log+ DELETE FROM blob_storage_file_logWHERE project_id = {projectId: String}AND created_at <= {beforeDate: DateTime64(3)};`;@@ -258,3 +259,74 @@ export const deleteEventLogByProjectIdBeforeDate = async (},});};++// this function is only used for the background migration from event_log to blob_storage_file_log+export const insertIntoS3RefsTableFromEventLog = async (+ limit: number,+ offset: number,+) => {+ const query = `+ INSERT INTO blob_storage_file_log+ SELECT+ id,+ project_id,+ entity_type,+ entity_id,+ event_id,+ bucket_name,+ bucket_path,+ created_at,+ updated_at,+ created_at AS event_ts,+ 0 AS is_deleted+ FROM event_log+ ORDER BY (project_id, entity_type, entity_id, bucket_path) DESC+ LIMIT {limit: Int32}+ OFFSET {offset: Int32}+ `;++ await commandClickhouse({+ query,+ params: {+ limit,+ offset,+ },+ tags: {+ feature: "backgroundMigration",+ kind: "list",+ },+ });+};++export const getLastEventLogPrimaryKey = async () => {+ const query = `+ SELECT project_id, entity_type, entity_id, bucket_path+ FROM event_log+ ORDER BY (project_id, entity_type, entity_id, bucket_path) ASC+ LIMIT 1+ `;+ const result = await queryClickhouse<{+ project_id: string;+ entity_type: string;+ entity_id: string;+ bucket_path: string;+ }>({ query });+ return result.shift();+};++export const findS3RefsByPrimaryKey = async (primaryKey: {+ project_id: string;+ entity_type: string;+ entity_id: string;+ bucket_path: string;+}) => {+ const query = `+ SELECT *+ FROM blob_storage_file_log+ WHERE project_id = {project_id: String}+ AND entity_type = {entity_type: String}+ AND entity_id = {entity_id: String}+ AND bucket_path = {bucket_path: String}+ `;+ return queryClickhouse<EventLogRecordReadType>({ query, params: primaryKey });+};diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex 5625093500..59a414bdb4 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -60,7 +60,7 @@ export async function upsertClickhouse<await clickhouseClient({tags: opts.tags,}).insert({- table: "event_log",+ table: "blob_storage_file_log",values: [{id: randomUUID(),@@ -70,6 +70,8 @@ export async function upsertClickhouse<event_id: eventId,bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,bucket_path: bucketPath,+ event_ts: convertDateToClickhouseDateTime(new Date()),+ is_deleted: 0,},],format: "JSONEachRow",diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex f37a363719..bb6c4a587c 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -157,7 +157,7 @@ export const scoreRecordInsertSchema = scoreRecordBaseSchema.extend({});export type ScoreRecordInsertType = z.infer<typeof scoreRecordInsertSchema>;-export const eventLogRecordBaseSchema = z.object({+export const blobStorageFileLogRecordBaseSchema = z.object({id: z.string(),project_id: z.string(),entity_type: z.string(),@@ -167,18 +167,23 @@ export const eventLogRecordBaseSchema = z.object({event_id: z.string().nullable(),bucket_name: z.string(),bucket_path: z.string(),+ is_deleted: z.number(),});-export const eventLogRecordReadSchema = eventLogRecordBaseSchema.extend({- created_at: clickhouseStringDateSchema,- updated_at: clickhouseStringDateSchema,-});+export const eventLogRecordReadSchema =+ blobStorageFileLogRecordBaseSchema.extend({+ created_at: clickhouseStringDateSchema,+ updated_at: clickhouseStringDateSchema,+ event_ts: clickhouseStringDateSchema,+ });export type EventLogRecordReadType = z.infer<typeof eventLogRecordReadSchema>;-export const eventLogRecordInsertSchema = eventLogRecordBaseSchema.extend({- created_at: z.number(),- updated_at: z.number(),-});-export type EventLogRecordInsertType = z.infer<- typeof eventLogRecordInsertSchema+export const blobStorageFileLogRecordInsertSchema =+ blobStorageFileLogRecordBaseSchema.extend({+ created_at: z.number(),+ updated_at: z.number(),+ event_ts: z.number(),+ });+export type BlobStorageFileLogInsertType = z.infer<+ typeof blobStorageFileLogRecordInsertSchema>;export const convertTraceReadToInsert = (diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex 59534c95c3..eb0d7bff08 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -9,5 +9,5 @@ export * from "./observations_converters";export * from "./clickhouse";export * from "./constants";export * from "./trace-sessions";-export * from "./eventLog";+export * from "./blobStorageLog";export * from "./environments";diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.tsindex e0e7b26089..32aab03b79 100644--- a/web/src/__tests__/async/ingestion-api.servertest.ts+++ b/web/src/__tests__/async/ingestion-api.servertest.ts@@ -2,7 +2,7 @@ import { randomUUID } from "crypto";import { makeAPICall } from "@/src/__tests__/test-utils";import waitForExpect from "wait-for-expect";import {- getEventLogByProjectAndEntityId,+ getBlobStorageByProjectAndEntityId,getObservationById,getScoreById,getTraceById,@@ -486,7 +486,7 @@ describe("/api/public/ingestion API Endpoint", () => {expect(response.status).toBe(207);await waitForExpect(async () => {- const logs = await getEventLogByProjectAndEntityId(+ const logs = await getBlobStorageByProjectAndEntityId(projectId,"trace",traceId,diff --git a/worker/src/__tests__/dataRetentionProcessing.test.ts b/worker/src/__tests__/dataRetentionProcessing.test.tsindex 1d4141b5c3..d032d3bd5b 100644--- a/worker/src/__tests__/dataRetentionProcessing.test.ts+++ b/worker/src/__tests__/dataRetentionProcessing.test.ts@@ -9,7 +9,7 @@ import {createScoresCh,createTrace,createTracesCh,- getEventLogByProjectAndEntityId,+ getBlobStorageByProjectAndEntityId,getObservationById,getScoreById,getTraceById,@@ -28,7 +28,7 @@ describe("DataRetentionProcessingJob", () => {storageService = StorageServiceFactory.getInstance({accessKeyId: env.LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID,secretAccessKey: env.LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY,- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),endpoint: env.LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT,region: env.LANGFUSE_S3_MEDIA_UPLOAD_REGION,forcePathStyle: env.LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE === "true",@@ -50,7 +50,7 @@ describe("DataRetentionProcessingJob", () => {});await clickhouseClient().insert({- table: "event_log",+ table: "blob_storage_file_log",format: "JSONEachRow",values: [{@@ -76,7 +76,7 @@ describe("DataRetentionProcessingJob", () => {const files = await storageService.listFiles("");expect(files.map((file) => file.file)).toContain(fileName);- const eventLogRecord = await getEventLogByProjectAndEntityId(+ const eventLogRecord = await getBlobStorageByProjectAndEntityId(projectId,"trace",`${baseId}-trace`,@@ -99,7 +99,7 @@ describe("DataRetentionProcessingJob", () => {});await clickhouseClient().insert({- table: "event_log",+ table: "blob_storage_file_log",format: "JSONEachRow",values: [{@@ -125,7 +125,7 @@ describe("DataRetentionProcessingJob", () => {const files = await storageService.listFiles("");expect(files.map((file) => file.file)).not.toContain(fileName);- const eventLogRecord = await getEventLogByProjectAndEntityId(+ const eventLogRecord = await getBlobStorageByProjectAndEntityId(projectId,"trace",`${baseId}-trace`,@@ -155,7 +155,7 @@ describe("DataRetentionProcessingJob", () => {projectId,createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), // 3 days in the pastbucketPath: fileName,- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),contentType: fileType,contentLength: 0,},@@ -213,7 +213,7 @@ describe("DataRetentionProcessingJob", () => {projectId,createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30), // 30 days in the pastbucketPath: fileName,- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),contentType: fileType,contentLength: 0,},diff --git a/worker/src/__tests__/projectDeletionProcessing.test.ts b/worker/src/__tests__/projectDeletionProcessing.test.tsindex 345539405e..35f16a0958 100644--- a/worker/src/__tests__/projectDeletionProcessing.test.ts+++ b/worker/src/__tests__/projectDeletionProcessing.test.ts@@ -9,7 +9,7 @@ import {createScoresCh,createTrace,createTracesCh,- getEventLogByProjectAndEntityId,+ getBlobStorageByProjectAndEntityId,getObservationById,getScoreById,getTraceById,@@ -29,7 +29,7 @@ describe("ProjectDeletionProcessingJob", () => {storageService = StorageServiceFactory.getInstance({accessKeyId: env.LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID,secretAccessKey: env.LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY,- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),endpoint: env.LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT,region: env.LANGFUSE_S3_MEDIA_UPLOAD_REGION,forcePathStyle: env.LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE === "true",@@ -176,7 +176,7 @@ describe("ProjectDeletionProcessingJob", () => {false,);- const eventLogRecord = await getEventLogByProjectAndEntityId(+ const eventLogRecord = await getBlobStorageByProjectAndEntityId(projectId,"trace",`${baseId}-trace`,@@ -215,7 +215,7 @@ describe("ProjectDeletionProcessingJob", () => {projectId,createdAt: new Date(),bucketPath: fileName,- bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,+ bucketName: String(env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET),contentType: fileType,contentLength: 0,},diff --git a/worker/src/__tests__/scoreDeletion.test.ts b/worker/src/__tests__/scoreDeletion.test.tsindex 2cbb64666b..ae5c0e58e4 100644--- a/worker/src/__tests__/scoreDeletion.test.ts+++ b/worker/src/__tests__/scoreDeletion.test.ts@@ -4,7 +4,7 @@ import {createOrgProjectAndApiKey,createScore,createScoresCh,- getEventLogByProjectId,+ getBlobStorageByProjectId,getScoresByIds,StorageService,StorageServiceFactory,@@ -62,7 +62,7 @@ describe("score deletion", () => {]);await clickhouseClient().insert({- table: "event_log",+ table: "blob_storage_file_log",format: "JSONEachRow",values: [{@@ -83,7 +83,7 @@ describe("score deletion", () => {await processClickhouseScoreDelete(projectId, [scoreId]);// Then- const eventLog = getEventLogByProjectId(projectId);+ const eventLog = getBlobStorageByProjectId(projectId);for await (const _ of eventLog) {// Should never happen as the expect event log to be emptyexpect(true).toBe(false);diff --git a/worker/src/__tests__/traceDeletion.test.ts b/worker/src/__tests__/traceDeletion.test.tsindex c7e1b03ec8..1234df84a3 100644--- a/worker/src/__tests__/traceDeletion.test.ts+++ b/worker/src/__tests__/traceDeletion.test.ts@@ -8,7 +8,7 @@ import {createScoresCh,createTrace,createTracesCh,- getEventLogByProjectId,+ getBlobStorageByProjectId,getObservationsForTrace,getScoresForTraces,getTracesByIds,@@ -290,7 +290,7 @@ describe("trace deletion", () => {]);await clickhouseClient().insert({- table: "event_log",+ table: "blob_storage_file_log",format: "JSONEachRow",values: [{@@ -333,7 +333,7 @@ describe("trace deletion", () => {await processClickhouseTraceDelete(projectId, [traceId]);// Then- const eventLog = getEventLogByProjectId(projectId);+ const eventLog = getBlobStorageByProjectId(projectId);for await (const _ of eventLog) {// Should never happen as the expect event log to be emptyexpect(true).toBe(false);diff --git a/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts b/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.tsnew file mode 100644index 0000000000..10dd74c280--- /dev/null+++ b/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts@@ -0,0 +1,196 @@+import { IBackgroundMigration } from "./IBackgroundMigration";+import {+ clickhouseClient,+ findS3RefsByPrimaryKey,+ getLastEventLogPrimaryKey,+ insertIntoS3RefsTableFromEventLog,+ logger,+} from "@langfuse/shared/src/server";+import { parseArgs } from "node:util";+import { prisma } from "@langfuse/shared/src/db";+import { env } from "../env";++// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table++type MigrationState = {+ offset: number;+};++const backgroundMigrationId = "c19b91d9-f9a2-468b-8209-95578f970c5b";++export default class MigrateEventLogToBlobStorageRefTable+ implements IBackgroundMigration+{+ private isAborted = false;+ private isFinished = false;++ async validate(+ args: Record<string, unknown>,+ attempts = 5,+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {+ // Check if Clickhouse credentials are configured+ if (+ !env.CLICKHOUSE_URL ||+ !env.CLICKHOUSE_USER ||+ !env.CLICKHOUSE_PASSWORD+ ) {+ return {+ valid: false,+ invalidReason:+ "Clickhouse credentials must be configured to perform migration",+ };+ }++ // Check if ClickHouse traces table exists+ const tables = await clickhouseClient().query({+ query: "SHOW TABLES",+ });+ const tableNames = (await tables.json()).data as { name: string }[];+ if (+ !tableNames.some((r) => r.name === "event_log") ||+ !tableNames.some((r) => r.name === "blob_storage_file_log")+ ) {+ // Retry if the table does not exist as this may mean migrations are still pending+ if (attempts > 0) {+ logger.info(+ `ClickHouse event_log or blob_storage_file_log tables do not exist. Retrying in 10s...`,+ );+ return new Promise((resolve) => {+ setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);+ });+ }++ // If all retries are exhausted, return as invalid+ return {+ valid: false,+ invalidReason:+ "ClickHouse event_log or blob_storage_file_log tables do not exist",+ };+ }++ return { valid: true, invalidReason: undefined };+ }++ async run(args: Record<string, unknown>): Promise<void> {+ const start = Date.now();+ logger.info(+ `Migrating from event_log table to blob_storage_file_log with ${JSON.stringify(args)}`,+ );++ // @ts-ignore+ const initialMigrationState: {+ state: MigrationState;+ } = await prisma.backgroundMigration.findUniqueOrThrow({+ where: { id: backgroundMigrationId },+ select: { state: true },+ });++ const maxRowsToProcess = Number(args.maxRowsToProcess ?? Infinity);+ const batchSize = Number(args.batchSize ?? 200_000);++ const initialState = initialMigrationState.state.offset+ ? initialMigrationState.state+ : {+ offset: Number(args.offset ?? 0),+ };++ await prisma.backgroundMigration.update({+ where: { id: backgroundMigrationId },+ data: { state: initialState },+ });+ let processedRows = 0;+ while (+ !this.isAborted &&+ !this.isFinished &&+ processedRows < maxRowsToProcess+ ) {+ const fetchStart = Date.now();++ // @ts-ignore+ const migrationState: { state: MigrationState } =+ await prisma.backgroundMigration.findUniqueOrThrow({+ where: { id: backgroundMigrationId },+ select: { state: true },+ });++ // ordered by time ascending.+ await insertIntoS3RefsTableFromEventLog(+ batchSize,+ migrationState.state.offset,+ );++ logger.info(+ `Inserted up to ${batchSize} records into blob_storage_file_log in ${Date.now() - fetchStart}ms`,+ );++ const lastEventLogPrimaryKey = await getLastEventLogPrimaryKey();++ if (!lastEventLogPrimaryKey) {+ logger.info("Event log table is empty. Exiting...");+ break;+ }++ const s3Refs = await findS3RefsByPrimaryKey(lastEventLogPrimaryKey);++ if (s3Refs.length > 0) {+ logger.info("No more event logs to migrate. Exiting...");+ this.isFinished = true;+ }++ await prisma.backgroundMigration.update({+ where: { id: backgroundMigrationId },+ data: {+ state: {+ offset: migrationState.state.offset + batchSize,+ },+ },+ });+ }++ if (this.isAborted) {+ logger.info(+ `Migration of event_log table to blob storage log aborted after processing ${processedRows} rows. Skipping cleanup.`,+ );+ return;+ }++ logger.info(+ `Finished migration of event_log table to blob storage log in ${Date.now() - start}ms`,+ );+ }++ async abort(): Promise<void> {+ logger.info(`Aborting migration of event_log table to blob storage log`);+ this.isAborted = true;+ }+}++async function main() {+ const args = parseArgs({+ options: {+ batchSize: { type: "string", short: "b", default: "1000" },+ maxRowsToProcess: { type: "string", short: "r", default: "Infinity" },+ maxDate: {+ type: "string",+ short: "d",+ default: new Date("1970-01-01T00:00:00.000Z").toISOString(),+ },+ },+ });++ const migration = new MigrateEventLogToBlobStorageRefTable();+ await migration.validate(args.values);+ await migration.run(args.values);+}++// If the script is being executed directly (not imported), run the main function+if (require.main === module) {+ main()+ .then(() => {+ process.exit(0);+ })+ .catch((error) => {+ logger.error(`Migration execution failed: ${error}`, error);+ process.exit(1); // Exit with an error code+ });+}diff --git a/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts b/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.tsindex ef77ad7b0f..93978998da 100644--- a/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts+++ b/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts@@ -1,9 +1,9 @@import {- deleteEventLogByProjectIdBeforeDate,+ deleteBlobStorageByProjectIdBeforeDate,deleteObservationsOlderThanDays,deleteScoresOlderThanDays,deleteTracesOlderThanDays,- getEventLogByProjectIdBeforeDate,+ getBlobStorageByProjectIdBeforeDate,logger,StorageService,StorageServiceFactory,@@ -91,7 +91,7 @@ export const handleDataRetentionProcessingJob = async (job: Job) => {}// Remove event files from S3- const eventLogStream = getEventLogByProjectIdBeforeDate(+ const eventLogStream = getBlobStorageByProjectIdBeforeDate(projectId,cutoffDate,);@@ -118,7 +118,7 @@ export const handleDataRetentionProcessingJob = async (job: Job) => {deleteTracesOlderThanDays(projectId, cutoffDate),deleteObservationsOlderThanDays(projectId, cutoffDate),deleteScoresOlderThanDays(projectId, cutoffDate),- deleteEventLogByProjectIdBeforeDate(projectId, cutoffDate),+ deleteBlobStorageByProjectIdBeforeDate(projectId, cutoffDate),]);logger.info(`[Data Retention] Deleted ClickHouse data older than ${retention} days for project ${projectId}`,diff --git a/worker/src/features/scores/processClickhouseScoreDelete.ts b/worker/src/features/scores/processClickhouseScoreDelete.tsindex c38a7920e7..f5c2374092 100644--- a/worker/src/features/scores/processClickhouseScoreDelete.ts+++ b/worker/src/features/scores/processClickhouseScoreDelete.ts@@ -1,11 +1,11 @@import {deleteScores,- deleteEventLogByProjectIdAndIds,logger,StorageService,StorageServiceFactory,traceException,- getEventLogByProjectIdAndEntityIds,+ getBlobStorageByProjectIdAndEntityIds,+ deleteBlobStorageByProjectIdAndIds,} from "@langfuse/shared/src/server";import { env } from "../../env";@@ -33,7 +33,7 @@ export const processClickhouseScoreDelete = async (`Deleting scores ${JSON.stringify(scoreIds)} in project ${projectId} from Clickhouse`,);- const eventLogStream = getEventLogByProjectIdAndEntityIds(+ const eventLogStream = getBlobStorageByProjectIdAndEntityIds(projectId,"score",scoreIds,@@ -47,7 +47,7 @@ export const processClickhouseScoreDelete = async (if (eventLogRecords.length > 500) {// Delete the current batch and reset the listawait eventStorageClient.deleteFiles(eventLogRecords.map((r) => r.path));- await deleteEventLogByProjectIdAndIds(+ await deleteBlobStorageByProjectIdAndIds(projectId,eventLogRecords.map((r) => r.id),);@@ -56,7 +56,7 @@ export const processClickhouseScoreDelete = async (}// Delete any remaining filesawait eventStorageClient.deleteFiles(eventLogRecords.map((r) => r.path));- await deleteEventLogByProjectIdAndIds(+ await deleteBlobStorageByProjectIdAndIds(projectId,eventLogRecords.map((r) => r.id),);diff --git a/worker/src/features/traces/processClickhouseTraceDelete.ts b/worker/src/features/traces/processClickhouseTraceDelete.tsindex 812af1936a..9b40d925d1 100644--- a/worker/src/features/traces/processClickhouseTraceDelete.ts+++ b/worker/src/features/traces/processClickhouseTraceDelete.ts@@ -1,9 +1,9 @@import {- deleteEventLogByProjectIdAndIds,+ deleteBlobStorageByProjectIdAndIds,deleteObservationsByTraceIds,deleteScoresByTraceIds,deleteTraces,- getEventLogByProjectIdAndTraceIds,+ getBlobStorageByProjectIdAndTraceIds,logger,StorageService,StorageServiceFactory,@@ -158,7 +158,10 @@ export const processClickhouseTraceDelete = async (await deleteMediaItemsForTraces(projectId, traceIds);- const eventLogStream = getEventLogByProjectIdAndTraceIds(projectId, traceIds);+ const eventLogStream = getBlobStorageByProjectIdAndTraceIds(+ projectId,+ traceIds,+ );let eventLogRecords: { id: string; path: string }[] = [];const eventStorageClient = getS3EventStorageClient(env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,@@ -168,7 +171,7 @@ export const processClickhouseTraceDelete = async (if (eventLogRecords.length > 500) {// Delete the current batch and reset the listawait eventStorageClient.deleteFiles(eventLogRecords.map((r) => r.path));- await deleteEventLogByProjectIdAndIds(+ await deleteBlobStorageByProjectIdAndIds(projectId,eventLogRecords.map((r) => r.id),);@@ -177,7 +180,7 @@ export const processClickhouseTraceDelete = async (}// Delete any remaining filesawait eventStorageClient.deleteFiles(eventLogRecords.map((r) => r.path));- await deleteEventLogByProjectIdAndIds(+ await deleteBlobStorageByProjectIdAndIds(projectId,eventLogRecords.map((r) => r.id),);diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsindex ab9fcc6393..737bacc2a3 100644--- a/worker/src/queues/ingestionQueue.ts+++ b/worker/src/queues/ingestionQueue.ts@@ -71,20 +71,23 @@ export const ingestionQueueProcessorBuilder = (// We write the new file into the ClickHouse event log to keep track for retention and deletionsconst clickhouseWriter = ClickhouseWriter.getInstance();- const fileName = job.data.payload.data.fileKey- ? `${job.data.payload.data.fileKey}.json`- : "";- clickhouseWriter.addToQueue(TableName.EventLog, {- id: randomUUID(),- project_id: job.data.payload.authCheck.scope.projectId,- entity_type: getClickhouseEntityType(job.data.payload.data.type),- entity_id: job.data.payload.data.eventBodyId,- event_id: job.data.payload.data.fileKey ?? null,- bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,- bucket_path: `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${getClickhouseEntityType(job.data.payload.data.type)}/${job.data.payload.data.eventBodyId}/${fileName}`,- created_at: new Date().getTime(),- updated_at: new Date().getTime(),- });++ if (job.data.payload.data.fileKey && job.data.payload.data.fileKey) {+ const fileName = `${job.data.payload.data.fileKey}.json`;+ clickhouseWriter.addToQueue(TableName.BlobStorageFileLog, {+ id: randomUUID(),+ project_id: job.data.payload.authCheck.scope.projectId,+ entity_type: getClickhouseEntityType(job.data.payload.data.type),+ entity_id: job.data.payload.data.eventBodyId,+ event_id: job.data.payload.data.fileKey,+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ bucket_path: `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${getClickhouseEntityType(job.data.payload.data.type)}/${job.data.payload.data.eventBodyId}/${fileName}`,+ created_at: new Date().getTime(),+ updated_at: new Date().getTime(),+ event_ts: new Date().getTime(),+ is_deleted: 0,+ });+ }// If fileKey was processed within the last minutes, i.e. has a match in redis, we skip processing.if (@@ -211,6 +214,7 @@ export const ingestionQueueProcessorBuilder = (// Perform merge of those eventsif (!redis) throw new Error("Redis not available");if (!prisma) throw new Error("Prisma not available");+await new IngestionService(redis,prisma,diff --git a/worker/src/queues/projectDelete.ts b/worker/src/queues/projectDelete.tsindex 4535b99e19..171219da91 100644--- a/worker/src/queues/projectDelete.ts+++ b/worker/src/queues/projectDelete.ts@@ -1,11 +1,11 @@import { Job, Processor } from "bullmq";import {- deleteEventLogByProjectId,+ deleteBlobStorageByProjectId,deleteObservationsByProjectId,deleteScoresByProjectId,deleteTracesByProjectId,getCurrentSpan,- getEventLogByProjectId,+ getBlobStorageByProjectId,logger,QueueName,StorageService,@@ -95,7 +95,7 @@ export const projectDeleteProcessor: Processor = async (// Remove event files from S3let batch = 0;- const eventLogStream = getEventLogByProjectId(projectId);+ const eventLogStream = getBlobStorageByProjectId(projectId);let eventLogPaths: string[] = [];const eventStorageClient = getS3EventStorageClient(env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,@@ -122,7 +122,7 @@ export const projectDeleteProcessor: Processor = async (deleteTracesByProjectId(projectId),deleteObservationsByProjectId(projectId),deleteScoresByProjectId(projectId),- deleteEventLogByProjectId(projectId),+ deleteBlobStorageByProjectId(projectId),]);logger.info(`Deleting PG data for project ${projectId} in org ${orgId}`);diff --git a/worker/src/scripts/refill-ingestion-events.ts b/worker/src/scripts/refill-ingestion-events.tsindex dd7ddee4e9..a6e820d63a 100644--- a/worker/src/scripts/refill-ingestion-events.ts+++ b/worker/src/scripts/refill-ingestion-events.ts@@ -68,6 +68,7 @@ const main = async () => {data: {type: eventType,eventBodyId: eventBodyId,+ fileKey: eventId,},authCheck: {validKey: true as const,diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex 571ab10002..48ace54e4e 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -1,7 +1,7 @@import {clickhouseClient,ClickhouseClientType,- EventLogRecordInsertType,+ BlobStorageFileLogInsertType,getCurrentSpan,ObservationRecordInsertType,recordGauge,@@ -38,7 +38,7 @@ export class ClickhouseWriter {[TableName.Traces]: [],[TableName.Scores]: [],[TableName.Observations]: [],- [TableName.EventLog]: [],+ [TableName.BlobStorageFileLog]: [],};this.start();@@ -103,7 +103,7 @@ export class ClickhouseWriter {this.flush(TableName.Traces, fullQueue),this.flush(TableName.Scores, fullQueue),this.flush(TableName.Observations, fullQueue),- this.flush(TableName.EventLog, fullQueue),+ this.flush(TableName.BlobStorageFileLog, fullQueue),]).catch((err) => {logger.error("ClickhouseWriter.flushAll", err);});@@ -239,7 +239,7 @@ export enum TableName {Traces = "traces",Scores = "scores",Observations = "observations",- EventLog = "event_log",+ BlobStorageFileLog = "blob_storage_file_log",}type RecordInsertType<T extends TableName> = T extends TableName.Scores@@ -248,8 +248,8 @@ type RecordInsertType<T extends TableName> = T extends TableName.Scores? ObservationRecordInsertType: T extends TableName.Traces? TraceRecordInsertType- : T extends TableName.EventLog- ? EventLogRecordInsertType+ : T extends TableName.BlobStorageFileLog+ ? BlobStorageFileLogInsertType: never;type ClickhouseQueue = {