🪢 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
feat: log all created s3 event files in clickhouse (#5476)
Steffen Schmitz8ede19d26358
diff --git a/packages/shared/clickhouse/migrations/clustered/0007_add_event_log.down.sql b/packages/shared/clickhouse/migrations/clustered/0007_add_event_log.down.sqlnew file mode 100644index 0000000000..24542e21ba--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0007_add_event_log.down.sql@@ -0,0 +1 @@+DROP TABLE event_log ON CLUSTER default;\ No newline at end of filediff --git a/packages/shared/clickhouse/migrations/clustered/0007_add_event_log.up.sql b/packages/shared/clickhouse/migrations/clustered/0007_add_event_log.up.sqlnew file mode 100644index 0000000000..9fa430da0e--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0007_add_event_log.up.sql@@ -0,0 +1,19 @@+CREATE TABLE event_log ON CLUSTER default+(+ `id` String,+ `project_id` String,+ `entity_type` String,+ `entity_id` String,+ `event_id` Nullable(String),++ `bucket_name` String,+ `bucket_path` String,++ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now()+) ENGINE = MergeTree()+ ORDER BY (+ project_id,+ entity_type,+ entity_id+ );diff --git a/packages/shared/clickhouse/migrations/unclustered/0007_add_event_log.down.sql b/packages/shared/clickhouse/migrations/unclustered/0007_add_event_log.down.sqlnew file mode 100644index 0000000000..3996548c5c--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0007_add_event_log.down.sql@@ -0,0 +1 @@+DROP TABLE event_log;\ No newline at end of filediff --git a/packages/shared/clickhouse/migrations/unclustered/0007_add_event_log.up.sql b/packages/shared/clickhouse/migrations/unclustered/0007_add_event_log.up.sqlnew file mode 100644index 0000000000..40afc72e63--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0007_add_event_log.up.sql@@ -0,0 +1,19 @@+CREATE TABLE event_log+(+ `id` String,+ `project_id` String,+ `entity_type` String,+ `entity_id` String,+ `event_id` Nullable(String),++ `bucket_name` String,+ `bucket_path` String,++ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now()+) ENGINE = MergeTree()+ ORDER BY (+ project_id,+ entity_type,+ entity_id+ );diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex f755d4aa5a..e059e8e360 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -158,6 +158,30 @@ export const scoreRecordInsertSchema = scoreRecordBaseSchema.extend({});export type ScoreRecordInsertType = z.infer<typeof scoreRecordInsertSchema>;+export const eventLogRecordBaseSchema = z.object({+ id: z.string(),+ project_id: z.string(),+ entity_type: z.string(),+ entity_id: z.string(),+ // event_id is nullable to be compatible with legacy queue events.+ // It still allows us to delete things by prefix, but requires an additional list call.+ event_id: z.string().nullable(),+ bucket_name: z.string(),+ bucket_path: z.string(),+});+export const eventLogRecordReadSchema = eventLogRecordBaseSchema.extend({+ created_at: clickhouseStringDateSchema,+ updated_at: 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 convertTraceReadToInsert = (record: TraceRecordReadType,): TraceRecordInsertType => {diff --git a/packages/shared/src/server/repositories/eventLog.ts b/packages/shared/src/server/repositories/eventLog.tsnew file mode 100644index 0000000000..9ffb30482b--- /dev/null+++ b/packages/shared/src/server/repositories/eventLog.ts@@ -0,0 +1,25 @@+import { queryClickhouse } from "./clickhouse";+import { EventLogRecordReadType } from "./definitions";++export const getEventLogByProjectAndEntityId = async (+ projectId: string,+ entityType: string,+ entityId: string,+): Promise<EventLogRecordReadType[]> => {+ const query = `+ select *+ from event_log+ where project_id = {projectId: String}+ and entity_type = {entityType: String}+ and entity_id = {entityId: String}+ `;++ return queryClickhouse<EventLogRecordReadType>({+ query,+ params: {+ projectId,+ entityType,+ entityId,+ },+ });+};diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex b07e848335..2038424076 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -9,3 +9,4 @@ export * from "./observations_converters";export * from "./clickhouse";export * from "./constants";export * from "./trace-sessions";+export * from "./eventLog";diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.tsindex 1846f94e89..99411770ff 100644--- a/web/src/__tests__/async/ingestion-api.servertest.ts+++ b/web/src/__tests__/async/ingestion-api.servertest.ts@@ -2,12 +2,12 @@ import { randomUUID } from "crypto";import { makeAPICall } from "@/src/__tests__/test-utils";import waitForExpect from "wait-for-expect";import {+ getEventLogByProjectAndEntityId,getObservationById,getScoreById,getTraceById,} from "@langfuse/shared/src/server";import { v4 } from "uuid";-import { prisma } from "@langfuse/shared/src/db";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";@@ -219,13 +219,14 @@ describe("/api/public/ingestion API Endpoint", () => {});// Disabled until eventLog becomes the default behaviour.- it.skip("should create a log entry for the S3 file", async () => {+ it("should create a log entry for the S3 file", async () => {const traceId = v4();+ const eventId = v4();const response = await makeAPICall("POST", "/api/public/ingestion", {batch: [{- id: v4(),+ id: eventId,type: "trace-create",timestamp: new Date().toISOString(),body: {@@ -241,13 +242,17 @@ describe("/api/public/ingestion API Endpoint", () => {});expect(response.status).toBe(207);- const logs = await prisma.eventLog.findMany({- where: {- entityType: "trace",- entityId: traceId,- },+ await waitForExpect(async () => {+ const logs = await getEventLogByProjectAndEntityId(+ projectId,+ "trace",+ traceId,+ );+ expect(logs.length).toBeGreaterThan(0);+ expect(logs[0].bucket_path).toBe(+ `events/${projectId}/trace/${traceId}/${eventId}.json`,+ );});- expect(logs.length).toBe(1);});it("#4900: should clear score comment on update with `null`", async () => {diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsindex 474a2f4d33..e0d19bc8c0 100644--- a/worker/src/queues/ingestionQueue.ts+++ b/worker/src/queues/ingestionQueue.ts@@ -1,26 +1,27 @@import { Job, Processor } from "bullmq";import {- traceException,- QueueName,- TQueueJobTypes,- logger,- IngestionEventType,- StorageServiceFactory,- StorageService,- redis,clickhouseClient,getClickhouseEntityType,getCurrentSpan,getQueue,+ IngestionEventType,+ logger,+ QueueName,recordDistribution,recordIncrement,+ redis,+ StorageService,+ StorageServiceFactory,+ TQueueJobTypes,+ traceException,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { env } from "../env";import { IngestionService } from "../services/IngestionService";-import { ClickhouseWriter } from "../services/ClickhouseWriter";+import { ClickhouseWriter, TableName } from "../services/ClickhouseWriter";import { chunk } from "lodash";+import { randomUUID } from "crypto";let s3StorageServiceClient: StorageService;@@ -68,6 +69,23 @@ export const ingestionQueueProcessorBuilder = ();}+ // We write the new file into the ClickHouse event log to keep track for retention and deletions+ const 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 fileKey was processed within the last minutes, i.e. has a match in redis, we skip processing.if (env.LANGFUSE_ENABLE_REDIS_SEEN_EVENT_CACHE === "true" &&@@ -196,7 +214,7 @@ export const ingestionQueueProcessorBuilder = (await new IngestionService(redis,prisma,- ClickhouseWriter.getInstance(),+ clickhouseWriter,clickhouseClient(),).mergeAndWrite(getClickhouseEntityType(events[0].type),diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex 3c582fc967..db3b30457c 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -1,5 +1,6 @@import {defaultClickhouseClient,+ EventLogRecordInsertType,getCurrentSpan,ObservationRecordInsertType,recordGauge,@@ -34,6 +35,7 @@ export class ClickhouseWriter {[TableName.Traces]: [],[TableName.Scores]: [],[TableName.Observations]: [],+ [TableName.EventLog]: [],};this.start();@@ -89,6 +91,7 @@ export class ClickhouseWriter {this.flush(TableName.Traces, fullQueue),this.flush(TableName.Scores, fullQueue),this.flush(TableName.Observations, fullQueue),+ this.flush(TableName.EventLog, fullQueue),]).catch((err) => {logger.error("ClickhouseWriter.flushAll", err);});@@ -219,6 +222,7 @@ export enum TableName {Traces = "traces",Scores = "scores",Observations = "observations",+ EventLog = "event_log",}type RecordInsertType<T extends TableName> = T extends TableName.Scores@@ -227,7 +231,9 @@ type RecordInsertType<T extends TableName> = T extends TableName.Scores? ObservationRecordInsertType: T extends TableName.Traces? TraceRecordInsertType- : never;+ : T extends TableName.EventLog+ ? EventLogRecordInsertType+ : never;type ClickhouseQueue = {[T in TableName]: ClickhouseWriterQueueItem<T>[];diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex b4b74acbbc..b6d3e6bc71 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -895,13 +895,22 @@ export class IngestionService {if (result.length === 0) return null;- return table === TableName.Traces- ? convertTraceReadToInsert(recordParser[table].parse(result[0]))- : table === TableName.Scores- ? convertScoreReadToInsert(recordParser[table].parse(result[0]))- : convertObservationReadToInsert(- recordParser[table].parse(result[0]),- );+ switch (table) {+ case TableName.Traces:+ return convertTraceReadToInsert(+ recordParser[table].parse(result[0]),+ );+ case TableName.Scores:+ return convertScoreReadToInsert(+ recordParser[table].parse(result[0]),+ );+ case TableName.Observations:+ return convertObservationReadToInsert(+ recordParser[table].parse(result[0]),+ );+ default:+ throw new Error(`Unsupported table name: ${table}`);+ }},);}