🪢 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 clickhouse ingestion to S3 based events (#3719)
Steffen Schmitz4a83749425ed
diff --git a/.env.prod.example b/.env.prod.exampleindex 6d4265639b..9db7f159af 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -238,10 +238,7 @@ OTEL_SERVICE_NAME="langfuse"# Ingestion# LANGFUSE_INGESTION_BUFFER_TTL_SECONDS=-# LANGFUSE_INGESTION_FLUSH_DELAY_MS=-# LANGFUSE_INGESTION_FLUSH_ATTEMPTS=-# LANGFUSE_INGESTION_FLUSH_PROCESSING_CONCURRENCY=-# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_BATCH_SIZE=+# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_BATCH_SIZE=# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=# LANGFUSE_INGESTION_CLICKHOUSE_MAX_ATTEMPTS=# LANGFUSE_LEGACY_INGESTION_WORKER_CONCURRENCY=diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 8b9a27c812..3b7d07f8b4 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -22,7 +22,7 @@ const EnvSchema = z.object({.string().length(64,- "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32"+ "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32",).optional(),LANGFUSE_CACHE_PROMPT_ENABLED: z.enum(["true", "false"]).default("false"),@@ -30,11 +30,6 @@ const EnvSchema = z.object({CLICKHOUSE_URL: z.string().url().optional(),CLICKHOUSE_USER: z.string().optional(),CLICKHOUSE_PASSWORD: z.string().optional(),- LANGFUSE_INGESTION_FLUSH_DELAY_MS: z.coerce- .number()- .nonnegative()- .default(10000),- LANGFUSE_INGESTION_FLUSH_ATTEMPTS: z.coerce.number().positive().default(3),LANGFUSE_INGESTION_BUFFER_TTL_SECONDS: z.coerce.number().positive()diff --git a/packages/shared/src/server/clickhouse.ts b/packages/shared/src/server/clickhouse.tsindex e0aed1c896..b1ad3fb575 100644--- a/packages/shared/src/server/clickhouse.ts+++ b/packages/shared/src/server/clickhouse.ts@@ -1,6 +1,35 @@import { createClient } from "@clickhouse/client";import { env } from "../env";+import { eventTypes, IngestionEventType } from "./ingestion/types";++export enum ClickhouseEntityType {+ Trace = "trace",+ Score = "score",+ Observation = "observation",+ SdkLog = "sdk-log",+}++export function getClickhouseEntityType(+ event: IngestionEventType,+): ClickhouseEntityType {+ switch (event.type) {+ case eventTypes.TRACE_CREATE:+ return ClickhouseEntityType.Trace;+ case eventTypes.OBSERVATION_CREATE:+ case eventTypes.OBSERVATION_UPDATE:+ case eventTypes.EVENT_CREATE:+ case eventTypes.SPAN_CREATE:+ case eventTypes.SPAN_UPDATE:+ case eventTypes.GENERATION_CREATE:+ case eventTypes.GENERATION_UPDATE:+ return ClickhouseEntityType.Observation;+ case eventTypes.SCORE_CREATE:+ return ClickhouseEntityType.Score;+ case eventTypes.SDK_LOG:+ return ClickhouseEntityType.SdkLog;+ }+}export type ClickhouseClientType = ReturnType<typeof createClient>;diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 71729cffc6..617a9bb875 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -11,16 +11,15 @@ export * from "./utils/DatabaseReadStream";export * from "./utils/transforms";export * from "./clickhouse";export * from "../server/definitions";-export * from "../server/ingestion/IngestionUtils";export * from "../server/ingestion/types";-export * from "../server/ingestion/model-match";+export * from "./ingestion/modelMatch";export * from "../server/ingestion/types";export * from "../server/ingestion/validateAndInflateScore";export * from "./redis/redis";-export * from "./redis/trace-upsert";-export * from "./redis/batch-export";-export * from "./redis/ingestionFlushQueue";-export * from "./redis/legacy-ingestion";+export * from "./redis/traceUpsert";+export * from "./redis/batchExport";+export * from "./redis/legacyIngestion";+export * from "./redis/ingestionQueue";export * from "./auth/types";export * from "./ingestion/legacy/index";export * from "./queues";diff --git a/packages/shared/src/server/ingestion/IngestionUtils.ts b/packages/shared/src/server/ingestion/IngestionUtils.tsdeleted file mode 100644index e4cbbd1125..0000000000--- a/packages/shared/src/server/ingestion/IngestionUtils.ts+++ /dev/null@@ -1,86 +0,0 @@-import { eventTypes, IngestionEventType } from "./types";--const reservedCharsEscapeMap = [- { reserved: ":", escape: "|%|" },- { reserved: "_", escape: "|#|" },-];--export enum ClickhouseEntityType {- Trace = "trace",- Score = "score",- Observation = "observation",- SDK_LOG = "sdk-log",-}--export class IngestionUtils {- public static getBufferKey(flushKey: string): string {- const { projectId, eventType, entityId } =- IngestionUtils.parseFlushKey(flushKey);-- const sanitizedEntityId = IngestionUtils.escapeReservedChars(entityId);-- return (- "ingestionBuffer:" + `${projectId}_${eventType}_${sanitizedEntityId}`- );- }-- public static getFlushKey(params: {- projectId: string;- eventType: ClickhouseEntityType;- entityId: string;- batchTimestamp: string;- }): string {- const { projectId, eventType, entityId, batchTimestamp } = params;- const sanitizedEntityId = IngestionUtils.escapeReservedChars(entityId);-- return `${projectId}_${eventType}_${sanitizedEntityId}_${batchTimestamp}`;- }-- public static parseFlushKey(projectEntityKey: string) {- const split = projectEntityKey.split("_");-- if (split.length < 3) {- throw new Error(- `Invalid project entity key format ${projectEntityKey}, expected 3 or 4 parts`- );- }-- const [projectId, eventType, escapedEntityId, batchTimestamp] = split;- const entityId = IngestionUtils.unescapeReservedChars(escapedEntityId);-- return { projectId, eventType, entityId, batchTimestamp };- }-- private static escapeReservedChars(string: string): string {- return reservedCharsEscapeMap.reduce(- (acc, { reserved, escape }) => acc.replaceAll(reserved, escape),- string- );- }-- private static unescapeReservedChars(escapedString: string): string {- return reservedCharsEscapeMap.reduce(- (acc, { reserved, escape }) => acc.replaceAll(escape, reserved),- escapedString- );- }-- public static getEventType(event: IngestionEventType): ClickhouseEntityType {- switch (event.type) {- case eventTypes.TRACE_CREATE:- return ClickhouseEntityType.Trace;- case eventTypes.OBSERVATION_CREATE:- case eventTypes.OBSERVATION_UPDATE:- case eventTypes.EVENT_CREATE:- case eventTypes.SPAN_CREATE:- case eventTypes.SPAN_UPDATE:- case eventTypes.GENERATION_CREATE:- case eventTypes.GENERATION_UPDATE:- return ClickhouseEntityType.Observation;- case eventTypes.SCORE_CREATE:- return ClickhouseEntityType.Score;- case eventTypes.SDK_LOG:- return ClickhouseEntityType.SDK_LOG;- }- }-}diff --git a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts b/packages/shared/src/server/ingestion/legacy/EventProcessor.tsindex 265e08fa52..ec6181597a 100644--- a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts+++ b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts@@ -1,7 +1,7 @@import { v4 } from "uuid";import { type z } from "zod";import Decimal from "decimal.js";-import { findModel } from "../model-match";+import { findModel } from "../modelMatch";import {ObservationEvent,eventTypes,@@ -117,11 +117,11 @@ export class ObservationProcessor implements EventProcessor {projectId: apiScope.projectId,model:"model" in this.event.body- ? this.event.body.model ?? undefined+ ? (this.event.body.model ?? undefined): undefined,unit:"usage" in this.event.body- ? this.event.body.usage?.unit ?? undefined+ ? (this.event.body.usage?.unit ?? undefined): undefined,startTime: this.event.body.startTime? new Date(this.event.body.startTime)@@ -158,10 +158,10 @@ export class ObservationProcessor implements EventProcessor {const newTotalCount ="usage" in this.event.body- ? this.event.body.usage?.total ??+ ? (this.event.body.usage?.total ??(newInputCount != null || newOutputCount != null? (newInputCount ?? 0) + (newOutputCount ?? 0)- : undefined)+ : undefined)): undefined;const userProvidedTokenCosts = {@@ -245,7 +245,7 @@ export class ObservationProcessor implements EventProcessor {model: "model" in this.event.body ? this.event.body.model : undefined,modelParameters:"modelParameters" in this.event.body- ? this.event.body.modelParameters ?? undefined+ ? (this.event.body.modelParameters ?? undefined): undefined,input: this.event.body.input ?? undefined,output: this.event.body.output ?? undefined,@@ -254,7 +254,7 @@ export class ObservationProcessor implements EventProcessor {totalTokens: newTotalCount,unit:"usage" in this.event.body- ? this.event.body.usage?.unit ?? internalModel?.unit+ ? (this.event.body.usage?.unit ?? internalModel?.unit): internalModel?.unit,level: this.event.body.level ?? undefined,statusMessage: this.event.body.statusMessage ?? undefined,@@ -300,7 +300,7 @@ export class ObservationProcessor implements EventProcessor {model: "model" in this.event.body ? this.event.body.model : undefined,modelParameters:"modelParameters" in this.event.body- ? this.event.body.modelParameters ?? undefined+ ? (this.event.body.modelParameters ?? undefined): undefined,input: this.event.body.input ?? undefined,output: this.event.body.output ?? undefined,@@ -309,7 +309,7 @@ export class ObservationProcessor implements EventProcessor {totalTokens: newTotalCount,unit:"usage" in this.event.body- ? this.event.body.usage?.unit ?? internalModel?.unit+ ? (this.event.body.usage?.unit ?? internalModel?.unit): internalModel?.unit,level: this.event.body.level ?? undefined,statusMessage: this.event.body.statusMessage ?? undefined,@@ -448,7 +448,7 @@ export class ObservationProcessor implements EventProcessor {const finalTotalCost =tokenCounts.total !== undefined && model?.totalPrice? model.totalPrice.mul(tokenCounts.total)- : finalInputCost ?? finalOutputCost+ : (finalInputCost ?? finalOutputCost)? new Decimal(finalInputCost ?? 0).add(finalOutputCost ?? 0): undefined;diff --git a/packages/shared/src/server/ingestion/legacy/enqueueIngestionEvents.ts b/packages/shared/src/server/ingestion/legacy/enqueueIngestionEvents.tsdeleted file mode 100644index 2675898311..0000000000--- a/packages/shared/src/server/ingestion/legacy/enqueueIngestionEvents.ts+++ /dev/null@@ -1,72 +0,0 @@-import { type Redis } from "ioredis";-import { QueueJobs } from "../../queues";-import {- getIngestionFlushQueue,- IngestionFlushQueue,-} from "../../redis/ingestionFlushQueue";-import { IngestionUtils } from "../IngestionUtils";-import { IngestionEventType } from "../types";-import { redis } from "../../redis/redis";-import { env } from "../../../env";-import { logger } from "../../logger";--export async function enqueueIngestionEvents(- projectId: string,- events: IngestionEventType[],-) {- const ingestionFlushQueue = getIngestionFlushQueue();-- if (!ingestionFlushQueue) {- throw Error("IngestionFlushQueue not initialized");- }- if (!redis) throw Error("Redis connection not available");-- const queuedEventPromises: Promise<void>[] = [];- const batchTimestamp = Date.now().toString();-- // Use for loop as TS does not narrow redis type in map function- for (const event of events) {- queuedEventPromises.push(- enqueueSingleIngestionEvent(- projectId,- event,- redis,- ingestionFlushQueue,- batchTimestamp,- ),- );- }-- await Promise.all(queuedEventPromises);-}--async function enqueueSingleIngestionEvent(- projectId: string,- event: IngestionEventType,- redis: Redis,- ingestionFlushQueue: IngestionFlushQueue,- batchTimestamp: string,-): Promise<void> {- if (!("id" in event.body && event.body.id)) {- logger.warn(- `Received ingestion event without id: ${JSON.stringify(event)}`,- );-- return;- }-- const flushKey = IngestionUtils.getFlushKey({- entityId: event.body.id,- eventType: IngestionUtils.getEventType(event),- projectId,- batchTimestamp,- });- const bufferKey = IngestionUtils.getBufferKey(flushKey);- const serializedEventData = JSON.stringify({ ...event, projectId });-- await redis.lpush(bufferKey, serializedEventData);- await redis.expire(bufferKey, env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS);- await ingestionFlushQueue.add(QueueJobs.FlushIngestionEntity, null, {- jobId: flushKey,- });-}diff --git a/packages/shared/src/server/ingestion/legacy/index.ts b/packages/shared/src/server/ingestion/legacy/index.tsindex 00253a2367..c07916d718 100644--- a/packages/shared/src/server/ingestion/legacy/index.ts+++ b/packages/shared/src/server/ingestion/legacy/index.ts@@ -7,12 +7,11 @@ import { TraceUpsertEventType } from "../../queues";import {convertTraceUpsertEventsToRedisEvents,getTraceUpsertQueue,-} from "../../redis/trace-upsert";+} from "../../redis/traceUpsert";import { ApiAccessScope } from "../../auth/types";import { redis } from "../../redis/redis";import { backOff } from "exponential-backoff";import { Model } from "../../..";-import { enqueueIngestionEvents } from "./enqueueIngestionEvents";import { logger } from "../../logger";export type BatchResult = {@@ -85,15 +84,6 @@ export const handleBatch = async (}}- if (env.CLICKHOUSE_URL) {- try {- await enqueueIngestionEvents(authCheck.scope.projectId, events);- logger.info(`Added ${events.length} ingestion events to queue`);- } catch (err) {- logger.error("Error adding ingestion events to queue", err);- }- }-return { results, errors };};diff --git a/packages/shared/src/server/ingestion/model-match.ts b/packages/shared/src/server/ingestion/modelMatch.tssimilarity index 100%rename from packages/shared/src/server/ingestion/model-match.tsrename to packages/shared/src/server/ingestion/modelMatch.tsdiff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex c6166c189d..2c7b5d0e29 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -1,5 +1,5 @@import { z } from "zod";-import { eventTypes, ingestionBatchEvent, TCarrier } from ".";+import { eventTypes, ingestionBatchEvent } from ".";export enum EventName {TraceUpsert = "TraceUpsert",@@ -28,7 +28,7 @@ export const LegacyIngestionEventMeta = z.object({type: z.nativeEnum(eventTypes),eventBodyId: z.string(),eventId: z.string(),- })+ }),),authCheck: z.object({validKey: z.literal(true),@@ -44,6 +44,20 @@ export const LegacyIngestionEvent = z.discriminatedUnion("useS3EventStore", [LegacyIngestionEventMeta,]);+export const IngestionEvent = z.object({+ data: z.object({+ type: z.nativeEnum(eventTypes),+ eventBodyId: z.string(),+ }),+ authCheck: z.object({+ validKey: z.literal(true),+ scope: z.object({+ projectId: z.string(),+ accessLevel: z.enum(["all", "scores"]),+ }),+ }),+});+export const BatchExportJobSchema = z.object({projectId: z.string(),batchExportId: z.string(),@@ -62,6 +76,7 @@ export type BatchExportJobType = z.infer<typeof BatchExportJobSchema>;export type TraceUpsertEventType = z.infer<typeof TraceUpsertEventSchema>;export type EvalExecutionEventType = z.infer<typeof EvalExecutionEvent>;export type LegacyIngestionEventType = z.infer<typeof LegacyIngestionEvent>;+export type IngestionEventQueueType = z.infer<typeof IngestionEvent>;export const EventBodySchema = z.union([z.object({@@ -84,8 +99,8 @@ export enum QueueName {EvaluationExecution = "evaluation-execution-queue", // Worker executes EvalsBatchExport = "batch-export-queue",RepeatQueue = "repeat-queue",- IngestionFlushQueue = "ingestion-flush-queue",- LegacyIngestionQueue = "legacy-ingestion-queue",+ IngestionQueue = "ingestion-queue", // Process single events with S3-merge+ LegacyIngestionQueue = "legacy-ingestion-queue", // Used for batch processing of IngestionCloudUsageMeteringQueue = "cloud-usage-metering-queue",}@@ -94,9 +109,9 @@ export enum QueueJobs {EvaluationExecution = "evaluation-execution-job",BatchExportJob = "batch-export-job",EnqueueBatchExportJobs = "enqueue-batch-export-jobs",- FlushIngestionEntity = "flush-ingestion-entity",LegacyIngestionJob = "legacy-ingestion-job",CloudUsageMeteringJob = "cloud-usage-metering-job",+ IngestionJob = "ingestion-job",}export type TQueueJobTypes = {@@ -105,27 +120,29 @@ export type TQueueJobTypes = {id: string;payload: TraceUpsertEventType;name: QueueJobs.TraceUpsert;- _tracecontext?: TCarrier;};[QueueName.EvaluationExecution]: {timestamp: Date;id: string;payload: EvalExecutionEventType;name: QueueJobs.EvaluationExecution;- _tracecontext?: TCarrier;};[QueueName.BatchExport]: {timestamp: Date;id: string;payload: BatchExportJobType;name: QueueJobs.BatchExportJob;- _tracecontext?: TCarrier;};[QueueName.LegacyIngestionQueue]: {timestamp: Date;id: string;payload: LegacyIngestionEventType;name: QueueJobs.LegacyIngestionJob;- _tracecontext?: TCarrier;+ };+ [QueueName.IngestionQueue]: {+ timestamp: Date;+ id: string;+ payload: IngestionEventQueueType;+ name: QueueJobs.IngestionJob;};};diff --git a/packages/shared/src/server/redis/batch-export.ts b/packages/shared/src/server/redis/batchExport.tssimilarity index 100%rename from packages/shared/src/server/redis/batch-export.tsrename to packages/shared/src/server/redis/batchExport.tsdiff --git a/packages/shared/src/server/redis/ingestionFlushQueue.ts b/packages/shared/src/server/redis/ingestionFlushQueue.tsdeleted file mode 100644index 0c5a41cdfc..0000000000--- a/packages/shared/src/server/redis/ingestionFlushQueue.ts+++ /dev/null@@ -1,33 +0,0 @@-import { Queue } from "bullmq";--import { env } from "../../env";-import { createNewRedisInstance } from "../redis/redis";-import { QueueName } from "../queues";--export type IngestionFlushQueue = Queue<null>;--let ingestionFlushQueue: IngestionFlushQueue | null = null;--export const getIngestionFlushQueue = () => {- if (ingestionFlushQueue) return ingestionFlushQueue;-- const connection = createNewRedisInstance();-- ingestionFlushQueue = connection- ? new Queue<null>(QueueName.IngestionFlushQueue, {- connection: connection,- defaultJobOptions: {- removeOnComplete: true, // Important: If not true, new jobs for that ID would be ignored as jobs in the complete set are still considered as part of the queue- removeOnFail: 100_000,- delay: env.LANGFUSE_INGESTION_FLUSH_DELAY_MS,- attempts: env.LANGFUSE_INGESTION_FLUSH_ATTEMPTS,- backoff: {- type: "exponential",- delay: 5000,- },- },- })- : null;-- return ingestionFlushQueue;-};diff --git a/packages/shared/src/server/redis/ingestionQueue.ts b/packages/shared/src/server/redis/ingestionQueue.tsnew file mode 100644index 0000000000..742e0e7f9f--- /dev/null+++ b/packages/shared/src/server/redis/ingestionQueue.ts@@ -0,0 +1,37 @@+import { Queue } from "bullmq";+import { QueueName, TQueueJobTypes } from "../queues";+import { createNewRedisInstance } from "./redis";++export class IngestionQueue {+ private static instance: Queue<+ TQueueJobTypes[QueueName.IngestionQueue]+ > | null = null;++ public static getInstance(): Queue<+ TQueueJobTypes[QueueName.IngestionQueue]+ > | null {+ if (IngestionQueue.instance) return IngestionQueue.instance;++ const newRedis = createNewRedisInstance({ enableOfflineQueue: false });++ IngestionQueue.instance = newRedis+ ? new Queue<TQueueJobTypes[QueueName.IngestionQueue]>(+ QueueName.IngestionQueue,+ {+ connection: newRedis,+ defaultJobOptions: {+ removeOnComplete: true,+ removeOnFail: 100_000,+ attempts: 5,+ backoff: {+ type: "exponential",+ delay: 5000,+ },+ },+ },+ )+ : null;++ return IngestionQueue.instance;+ }+}diff --git a/packages/shared/src/server/redis/legacy-ingestion.ts b/packages/shared/src/server/redis/legacyIngestion.tssimilarity index 100%rename from packages/shared/src/server/redis/legacy-ingestion.tsrename to packages/shared/src/server/redis/legacyIngestion.tsdiff --git a/packages/shared/src/server/redis/trace-upsert.ts b/packages/shared/src/server/redis/traceUpsert.tssimilarity index 100%rename from packages/shared/src/server/redis/trace-upsert.tsrename to packages/shared/src/server/redis/traceUpsert.tsdiff --git a/packages/shared/src/server/services/S3StorageService.ts b/packages/shared/src/server/services/S3StorageService.tsindex bf7dfb9c93..96a6061493 100644--- a/packages/shared/src/server/services/S3StorageService.ts+++ b/packages/shared/src/server/services/S3StorageService.ts@@ -1,6 +1,7 @@import type { Readable } from "stream";import {GetObjectCommand,+ ListObjectsV2Command,PutObjectCommand,S3Client,} from "@aws-sdk/client-s3";@@ -103,6 +104,23 @@ export class S3StorageService {}}+ public async listFiles(prefix: string): Promise<string[]> {+ const listCommand = new ListObjectsV2Command({+ Bucket: this.bucketName,+ Prefix: prefix,+ });++ try {+ const response = await this.client.send(listCommand);+ return (+ response.Contents?.flatMap((file) => (file.Key ? [file.Key] : [])) ?? []+ );+ } catch (err) {+ logger.error(`Failed to list files from S3 ${prefix}`, err);+ throw Error("Failed to list files from S3");+ }+ }+private async getSignedUrl(fileName: string,ttlSeconds: number,diff --git a/web/src/env.mjs b/web/src/env.mjsindex 47144882cf..02024a1e1b 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -172,6 +172,9 @@ export const env = createEnv({LANGFUSE_ASYNC_INGESTION_PROCESSING: z.enum(["true", "false"]).default("false"),+ LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING: z+ .enum(["true", "false"])+ .default("false"),LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: z.string().optional()@@ -385,6 +388,8 @@ export const env = createEnv({process.env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS,LANGFUSE_ASYNC_INGESTION_PROCESSING:process.env.LANGFUSE_ASYNC_INGESTION_PROCESSING,+ LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING:+ process.env.LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING,LANGFUSE_ALLOWED_ORGANIZATION_CREATORS:process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,LANGFUSE_INGESTION_BUFFER_TTL_SECONDS:diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 5fa74c9d12..f797f0384f 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -11,6 +11,7 @@ import {handleBatch,recordIncrement,getCurrentSpan,+ IngestionQueue,LegacyIngestionQueue,S3StorageService,instrumentAsync,@@ -250,6 +251,42 @@ export default async function handler(});}+ // Send each event individually to IngestionQueue for new processing+ if (+ env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" &&+ env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true" &&+ env.LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING === "true" &&+ redis &&+ !s3UploadErrored+ ) {+ const queue = IngestionQueue.getInstance();+ const results = await Promise.allSettled(+ sortedBatch.map(async (event) => {+ return queue+ ? queue.add(QueueJobs.IngestionJob, {+ id: randomUUID(),+ timestamp: new Date(),+ name: QueueJobs.IngestionJob as const,+ payload: {+ data: {+ type: event.type,+ eventBodyId: event.body.id ?? "",+ },+ authCheck,+ },+ })+ : Promise.reject("Failed to instantiate queue");+ }),+ );+ results.forEach((result) => {+ if (result.status === "rejected") {+ logger.error("Failed to add event to IngestionQueue", {+ error: result.reason,+ });+ }+ });+ }+// As part of the legacy processing we sent the entire batch to the worker.if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" && redis) {const queue = LegacyIngestionQueue.getInstance();diff --git a/worker/src/__tests__/redis-consumer.test.ts b/worker/src/__tests__/redis-consumer.test.tsindex 9f98252f3d..ac5be59be8 100644--- a/worker/src/__tests__/redis-consumer.test.ts+++ b/worker/src/__tests__/redis-consumer.test.ts@@ -41,8 +41,8 @@ describe.sequential("handle redis events", () => {}, 20_000);test("handle no matching queue worker", async () => {- // IngestionFlushQueue worker vs TraceUpsert producer- WorkerManager.register(QueueName.IngestionFlushQueue, async () => true);+ // IngestionQueue worker vs TraceUpsert producer+ WorkerManager.register(QueueName.IngestionQueue, async () => true);const traceUpsertQueue = getTraceUpsertQueue();diff --git a/worker/src/app.ts b/worker/src/app.tsindex e0c1359402..036e11d586 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -11,7 +11,6 @@ import {evalJobExecutorQueueProcessor,} from "./queues/evalQueue";import { batchExportQueueProcessor } from "./queues/batchExportQueue";-import { ingestionFlushQueueProcessor } from "./queues/ingestionFlushQueueExecutor";import { repeatQueueProcessor } from "./queues/repeatQueue";import { onShutdown } from "./utils/shutdown";@@ -21,6 +20,7 @@ import { cloudUsageMeteringQueueProcessor } from "./queues/cloudUsageMeteringQueimport { WorkerManager } from "./queues/workerManager";import { QueueName } from "@langfuse/shared/src/server";import { env } from "./env";+import { ingestionQueueProcessor } from "./queues/ingestionQueue";const app = express();@@ -69,14 +69,10 @@ if (env.QUEUE_CONSUMER_BATCH_EXPORT_QUEUE_IS_ENABLED === "true") {});}-if (env.QUEUE_CONSUMER_INGESTION_FLUSH_QUEUE_IS_ENABLED === "true") {- WorkerManager.register(- QueueName.IngestionFlushQueue,- ingestionFlushQueueProcessor,- {- concurrency: env.LANGFUSE_INGESTION_FLUSH_PROCESSING_CONCURRENCY,- },- );+if (env.QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED === "true") {+ WorkerManager.register(QueueName.IngestionQueue, ingestionQueueProcessor, {+ concurrency: env.LANGFUSE_INGESTION_QEUEUE_PROCESSING_CONCURRENCY,+ });}if (diff --git a/worker/src/env.ts b/worker/src/env.tsindex 11ab1f95f3..461fffa092 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -42,6 +42,10 @@ const EnvSchema = z.object({.number().positive().default(100),+ LANGFUSE_INGESTION_QEUEUE_PROCESSING_CONCURRENCY: z.coerce+ .number()+ .positive()+ .default(100),LANGFUSE_INGESTION_CLICKHOUSE_WRITE_BATCH_SIZE: z.coerce.number().positive()@@ -95,7 +99,7 @@ const EnvSchema = z.object({QUEUE_CONSUMER_CLOUD_USAGE_METERING_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),- QUEUE_CONSUMER_INGESTION_FLUSH_QUEUE_IS_ENABLED: z+ QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),QUEUE_CONSUMER_BATCH_EXPORT_QUEUE_IS_ENABLED: zdiff --git a/worker/src/queues/ingestionFlushQueueExecutor.ts b/worker/src/queues/ingestionFlushQueueExecutor.tsdeleted file mode 100644index 14c926411d..0000000000--- a/worker/src/queues/ingestionFlushQueueExecutor.ts+++ /dev/null@@ -1,79 +0,0 @@-import { Processor } from "bullmq";--import { redis, QueueJobs } from "@langfuse/shared/src/server";-import { prisma } from "@langfuse/shared/src/db";-import {- clickhouseClient,- logger,- getIngestionFlushQueue,- recordIncrement,- recordGauge,- recordHistogram,-} from "@langfuse/shared/src/server";-import { ClickhouseWriter } from "../services/ClickhouseWriter";-import { IngestionService } from "../services/IngestionService";--const ingestionFlushQueue = getIngestionFlushQueue();--export const ingestionFlushQueueProcessor: Processor = async (job) => {- if (job.name === QueueJobs.FlushIngestionEntity) {- const flushKey = job.id;- if (!flushKey) {- throw new Error("Flushkey not provided");- }-- // reduce the delay from the time to get the actual wait time- // from the point where the job was ready to be processed- const waitTime = Date.now() - job.timestamp - job.delay;- recordIncrement("langfuse.queue.ingestion_flush.request");- recordHistogram("langfuse.queue.ingestion_flush.wait_time", waitTime, {- unit: "milliseconds",- });-- try {- // Check dependencies- if (!redis) throw new Error("Redis not available");- if (!prisma) throw new Error("Prisma not available");- if (!ingestionFlushQueue)- throw new Error("Ingestion flush queue not available");-- // Flush ingestion buffer- const processingStartTime = Date.now();-- await new IngestionService(- redis,- prisma,- ClickhouseWriter.getInstance(),- clickhouseClient- ).flush(flushKey);-- // Log processing time- const processingTime = Date.now() - processingStartTime;- logger.debug(- `Prepared and scheduled CH-write in ${processingTime} ms for ${flushKey}`- );- recordHistogram(- "langfuse.queue.ingestion_flush.processing_time",- processingTime,- {- unit: "milliseconds",- }- );-- // Log queue size- await ingestionFlushQueue- .count()- .then((count) => {- logger.debug(`Ingestion flush queue length: ${count}`);- recordGauge("langfuse.queue.ingestion_flush.length", count, {- unit: "records",- });- return count;- })- .catch();- } catch (err) {- logger.error(`Error processing flush request for ${flushKey}`, err);- throw err;- }- }-};diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsnew file mode 100644index 0000000000..395355d509--- /dev/null+++ b/worker/src/queues/ingestionQueue.ts@@ -0,0 +1,149 @@+import { Job, Processor } from "bullmq";+import {+ traceException,+ QueueName,+ recordIncrement,+ recordGauge,+ recordHistogram,+ TQueueJobTypes,+ logger,+ IngestionEventType,+ S3StorageService,+ ingestionBatchEvent,+ ingestionEvent,+ IngestionQueue,+ redis,+ clickhouseClient,+ getClickhouseEntityType,+} 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";++let s3StorageServiceClient: S3StorageService;++const getS3StorageServiceClient = (bucketName: string): S3StorageService => {+ if (!s3StorageServiceClient) {+ s3StorageServiceClient = new S3StorageService({+ bucketName,+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,+ endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,+ forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ });+ }+ return s3StorageServiceClient;+};++export const ingestionQueueProcessor: Processor = async (+ job: Job<TQueueJobTypes[QueueName.IngestionQueue]>,+) => {+ try {+ const startTime = Date.now();++ if (+ env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED !== "true" ||+ !env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET+ ) {+ throw new Error(+ "S3 event store is not enabled but useS3EventStore is true",+ );+ }++ const s3Client = getS3StorageServiceClient(+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ );+ const eventName = job.data.payload.data.type.split("-").shift();+ if (!eventName) {+ throw new Error("Event name not found");+ }++ logger.info("Processing ingestion event", {+ projectId: job.data.payload.authCheck.scope.projectId,+ payload: job.data.payload.data,+ });++ // Download all events from folder into a local array+ const eventFiles = await s3Client.listFiles(+ `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${eventName}/${job.data.payload.data.eventBodyId}/`,+ );++ const events: IngestionEventType[] = (+ await Promise.all(+ eventFiles.map(async (key) => {+ const file = await s3Client.download(key);+ const parsedFile = JSON.parse(file);++ const parsed = ingestionBatchEvent.safeParse(parsedFile);+ if (parsed.success) {+ return parsed.data;+ } else {+ const parsed = ingestionEvent.safeParse(parsedFile);+ if (parsed.success) {+ return [parsed.data];+ } else {+ throw new Error(+ `Failed to parse event from S3: ${parsed.error.message}`,+ );+ }+ }+ }),+ )+ ).flat();++ if (events.length === 0) {+ logger.warn(+ `No events found for project ${job.data.payload.authCheck.scope.projectId} and event ${job.data.payload.data.eventBodyId}`,+ );+ return;+ }++ // Perform merge of those events+ if (!redis) throw new Error("Redis not available");+ if (!prisma) throw new Error("Prisma not available");+ await new IngestionService(+ redis,+ prisma,+ ClickhouseWriter.getInstance(),+ clickhouseClient,+ ).mergeAndWrite(+ getClickhouseEntityType(events[0]),+ job.data.payload.authCheck.scope.projectId,+ job.data.payload.data.eventBodyId,+ events,+ );++ const waitTime = Date.now() - job.timestamp;+ recordIncrement("langfuse.queue.ingestion.request");+ recordHistogram("langfuse.queue.ingestion.wait_time", waitTime, {+ unit: "milliseconds",+ });++ // Log queue size+ await IngestionQueue.getInstance()+ ?.count()+ .then((count) => {+ logger.debug(`Ingestion queue length: ${count}`);+ recordGauge("langfuse.queue.ingestion.length", count, {+ unit: "records",+ });+ return count;+ })+ .catch();+ recordHistogram(+ "langfuse.queue.ingestion.processing_time",+ Date.now() - startTime,+ { unit: "milliseconds" },+ );+ } catch (e) {+ logger.error(+ `Failed job ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,+ e,+ );+ traceException(e);+ throw e;+ }+};diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.tsindex 1a07ce983e..e9b963592a 100644--- a/worker/src/queues/legacyIngestionQueue.ts+++ b/worker/src/queues/legacyIngestionQueue.ts@@ -38,7 +38,7 @@ const getS3StorageServiceClient = (bucketName: string): S3StorageService => {};export const legacyIngestionQueueProcessor: Processor = async (- job: Job<TQueueJobTypes[QueueName.LegacyIngestionQueue]>+ job: Job<TQueueJobTypes[QueueName.LegacyIngestionQueue]>,) => {try {const startTime = Date.now();@@ -50,19 +50,19 @@ export const legacyIngestionQueueProcessor: Processor = async (!env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET) {throw new Error(- "S3 event store is not enabled but useS3EventStore is true"+ "S3 event store is not enabled but useS3EventStore is true",);}// If we used the S3 store we need to fetch the ingestionEvents from S3const s3Client = getS3StorageServiceClient(- env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,);ingestionEvents = (await Promise.all(job.data.payload.data.map(async (record) => {const eventName = record.type.split("-").shift();const file = await s3Client.download(- `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${eventName}/${record.eventBodyId}/${record.eventId}.json`+ `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${eventName}/${record.eventBodyId}/${record.eventId}.json`,);const parsedFile = JSON.parse(file);const parsed = ingestionBatchEvent.safeParse(parsedFile);@@ -75,11 +75,11 @@ export const legacyIngestionQueueProcessor: Processor = async (return [parsed.data];} else {throw new Error(- `Failed to parse event from S3: ${parsed.error.message}`+ `Failed to parse event from S3: ${parsed.error.message}`,);}}- })+ }),)).flat();} else {@@ -117,20 +117,20 @@ export const legacyIngestionQueueProcessor: Processor = async (const result = await handleBatch(ingestionEvents,job.data.payload.authCheck,- tokenCount+ tokenCount,);// send out REDIS requests to worker for all trace typesawait addTracesToTraceUpsertQueue(result.results,- job.data.payload.authCheck.scope.projectId+ job.data.payload.authCheck.scope.projectId,);// Log queue sizeawait LegacyIngestionQueue.getInstance()?.count().then((count) => {- logger.debug(`Legacy Ingestion flush queue length: ${count}`);+ logger.debug(`Legacy Ingestion queue length: ${count}`);recordGauge("langfuse.queue.legacy_ingestion.length", count, {unit: "records",});@@ -140,12 +140,12 @@ export const legacyIngestionQueueProcessor: Processor = async (recordHistogram("langfuse.queue.legacy_ingestion.processing_time",Date.now() - startTime,- { unit: "milliseconds" }+ { unit: "milliseconds" },);} catch (e) {logger.error(`Failed job legacy ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,- e+ e,);traceException(e);throw e;diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex af1d233b95..34ba233353 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -9,8 +9,6 @@ import {convertTraceReadToInsert,eventTypes,findModel,- ingestionEventWithProjectId,- IngestionEventWithProjectIdType,ObservationEvent,observationRecordInsertSchema,ObservationRecordInsertType,@@ -25,9 +23,9 @@ import {traceRecordReadSchema,ClickhouseClientType,validateAndInflateScore,- IngestionUtils,ClickhouseEntityType,PromptService,+ IngestionEventType,} from "@langfuse/shared/src/server";import { tokenCount } from "../../features/tokenisation/usage";@@ -75,53 +73,34 @@ export class IngestionService {this.promptService = new PromptService(prisma, redis);}- public async flush(flushKey: string): Promise<void> {- const bufferKey = IngestionUtils.getBufferKey(flushKey);- const eventList = (await this.redis.lrange(bufferKey, 0, -1))- .map((serializedEventData) => {- const parsed = ingestionEventWithProjectId.safeParse(- JSON.parse(serializedEventData),- );-- if (!parsed.success) {- logger.error(- `Failed to parse event ${serializedEventData} : ${parsed.error}`,- );-- return null;- }-- return parsed.data;- })- .filter(Boolean) as IngestionEventWithProjectIdType[];-- if (eventList.length === 0) {- throw new Error(- `No valid events found in buffer for flushKey ${flushKey}`,- );- }-- const { projectId, eventType, entityId } =- IngestionUtils.parseFlushKey(flushKey);+ public async mergeAndWrite(+ eventType: ClickhouseEntityType,+ projectId: string,+ eventBodyId: string,+ events: IngestionEventType[],+ ): Promise<void> {+ logger.info(+ `Merging ingestion ${eventType} event for project ${projectId} and event ${eventBodyId}`,+ );switch (eventType) {case ClickhouseEntityType.Trace:return await this.processTraceEventList({projectId,- entityId,- traceEventList: eventList as TraceEventType[],+ entityId: eventBodyId,+ traceEventList: events as TraceEventType[],});case ClickhouseEntityType.Observation:return await this.processObservationEventList({projectId,- entityId,- observationEventList: eventList as ObservationEvent[],+ entityId: eventBodyId,+ observationEventList: events as ObservationEvent[],});case ClickhouseEntityType.Score: {return await this.processScoreEventList({projectId,- entityId,- scoreEventList: eventList as ScoreEventType[],+ entityId: eventBodyId,+ scoreEventList: events as ScoreEventType[],});}}@@ -560,7 +539,7 @@ export class IngestionService {const finalTotalCost =tokenCounts.total_usage_units != null && model?.totalPrice? model.totalPrice.toNumber() * tokenCounts.total_usage_units- : finalInputCost ?? finalOutputCost+ : (finalInputCost ?? finalOutputCost)? (finalInputCost ?? 0) + (finalOutputCost ?? 0): undefined;@@ -704,7 +683,7 @@ export class IngestionService {newInputCount &&newOutputCount? newInputCount + newOutputCount- : newInputCount ?? newOutputCount);+ : (newInputCount ?? newOutputCount));const newUnit = "usage" in obs.body ? obs.body.usage?.unit : undefined;diff --git a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts b/worker/src/services/IngestionService/tests/IngestionService.unit.test.tsindex 8ee77bb30d..7667dad6b2 100644--- a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts@@ -1,25 +1,7 @@import { expect, describe, it, vi } from "vitest";import { IngestionService } from "../../IngestionService";-import { IngestionUtils } from "@langfuse/shared/src/server";describe("IngestionService unit tests", () => {- it("correctly escapes user provided IDs", async () => {- const validUuid = "123e4567-e89b-12d3-a456-426614174000";- const userProvidedId = "user_provided_id_with:colon:chars";- const expectedEscapedId = "user|#|provided|#|id|#|with|%|colon|%|chars";-- expect((IngestionUtils as any).escapeReservedChars(userProvidedId)).toBe(- expectedEscapedId- );- expect(- (IngestionUtils as any).unescapeReservedChars(expectedEscapedId)- ).toBe(userProvidedId);-- expect((IngestionUtils as any).escapeReservedChars(validUuid)).toBe(- validUuid- );- });-it("correctly sorts events in ascending order by timestamp", async () => {const firstTrace = { timestamp: 1, type: "observation-create" };const secondTrace = { timestamp: 1, type: "observation-update" };@@ -28,7 +10,7 @@ describe("IngestionService unit tests", () => {const records = [thirdTrace, secondTrace, firstTrace];const sortedEventList = (IngestionService as any).toTimeSortedEventList(- records+ records,);expect(sortedEventList).toEqual([firstTrace, secondTrace, thirdTrace]);