🪢 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: use s3 event store to avoid event data in redis (#3537)
Steffen Schmitz0a88294202da
diff --git a/.env.dev.example b/.env.dev.exampleindex faaf87cd7b..b6402925e2 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -34,11 +34,25 @@ EMAIL_FROM_ADDRESS="" # Defines the email address to use as the from address.SMTP_CONNECTION_URL="" # Defines the connection url for smtp server.# S3 storage-S3_ENDPOINT=-S3_ACCESS_KEY_ID=-S3_SECRET_ACCESS_KEY=-S3_BUCKET_NAME=-S3_REGION=+S3_ENDPOINT=http://localhost:9090+S3_ACCESS_KEY_ID=minio+S3_SECRET_ACCESS_KEY=miniosecret+S3_BUCKET_NAME=mybucket+S3_REGION=us-east-1+## Necessary for minio compatibility+S3_FORCE_PATH_STYLE=true++# S3 Event Bucket Upload+## Set to true to test uploading all events to S3+LANGFUSE_S3_EVENT_UPLOAD_ENABLED=false+LANGFUSE_S3_EVENT_UPLOAD_BUCKET=mybucket+LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID=minio+LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY=miniosecret+LANGFUSE_S3_EVENT_UPLOAD_REGION=us-east-1+LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT=http://localhost:9090+## Necessary for minio compatibility+LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE=true+LANGFUSE_S3_EVENT_UPLOAD_PREFIX=events/# Set during docker build of application# Used to disable environment verification at build timediff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex d51d6c6170..45bf3666d9 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -98,7 +98,7 @@ jobs:- name: Load default envrun: |cp .env.dev.example .env- grep -v -e '^REDIS_HOST=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev.example > .env+ grep -v -e '^S3_BUCKET_NAME=' -e '^REDIS_HOST=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev.example > .env- name: Run + migraterun: |diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex b4246a8756..ed0d61ded8 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -17,6 +17,38 @@ services:depends_on:- postgres+ minio:+ image: minio/minio+ container_name: minio+ command: server /data --console-address ":9001"+ environment:+ MINIO_ACCESS_KEY: minio+ MINIO_SECRET_KEY: miniosecret+ ports:+ - "9090:9000"+ - "9091:9001"+ volumes:+ - langfuse_minio_data:/data+ healthcheck:+ test: ["CMD", "mc", "ready", "local"]+ interval: 10s+ timeout: 5s+ retries: 5+ start_period: 5s++ miniocreatebucket:+ image: minio/mc+ container_name: miniocreatebucket+ entrypoint: ["/bin/sh", "-c"]+ command: >+ "mc alias set minio http://minio:9000 minio miniosecret &&+ mc rm -r --force minio/mybucket || true &&+ mc mb minio/mybucket &&+ mc policy set download minio/mybucket"+ depends_on:+ minio:+ condition: service_healthy+redis:image: redis:7.2.4restart: always@@ -45,3 +77,5 @@ volumes:driver: locallangfuse_clickhouse_logs:driver: local+ langfuse_minio_data:+ driver: localdiff --git a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts b/packages/shared/src/server/ingestion/legacy/EventProcessor.tsindex 0363eab93d..265e08fa52 100644--- a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts+++ b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts@@ -10,6 +10,7 @@ import {traceEvent,scoreEvent,sdkLogEvent,+ ingestionEvent,} from "../types";import { validateAndInflateScore } from "../validateAndInflateScore";import { Trace, Observation, Score, Prisma, Model } from "@prisma/client";@@ -19,16 +20,41 @@ import { jsonSchema } from "../../../utils/zod";import { prisma } from "../../../db";import { LegacyIngestionAccessScope } from ".";import { logger } from "../../logger";-import { ApiAccessScope } from "../../auth/types";export interface EventProcessor {auth(apiScope: LegacyIngestionAccessScope): void;process(- apiScope: LegacyIngestionAccessScope+ apiScope: LegacyIngestionAccessScope,): Promise<Trace | Observation | Score> | undefined;}+export const getProcessorForEvent = (+ event: z.infer<typeof ingestionEvent>,+ calculateTokenDelegate: (p: {+ model: Model;+ text: unknown;+ }) => number | undefined,+): EventProcessor => {+ switch (event.type) {+ case eventTypes.TRACE_CREATE:+ return new TraceProcessor(event);+ 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 new ObservationProcessor(event, calculateTokenDelegate);+ case eventTypes.SCORE_CREATE: {+ return new ScoreProcessor(event);+ }+ case eventTypes.SDK_LOG:+ return new SdkLogProcessor(event);+ }+};+export class ObservationProcessor implements EventProcessor {event: ObservationEvent;calculateTokenDelegate: (p: {@@ -41,7 +67,7 @@ export class ObservationProcessor implements EventProcessor {calculateTokenDelegate: (p: {model: Model;text: unknown;- }) => number | undefined+ }) => number | undefined,) {this.event = event;this.calculateTokenDelegate = calculateTokenDelegate;@@ -49,7 +75,7 @@ export class ObservationProcessor implements EventProcessor {async convertToObservation(apiScope: LegacyIngestionAccessScope,- existingObservation: Omit<Observation, "input" | "output"> | null+ existingObservation: Omit<Observation, "input" | "output"> | null,): Promise<{id: string;create: Prisma.ObservationUncheckedCreateInput;@@ -79,7 +105,7 @@ export class ObservationProcessor implements EventProcessor {!existingObservation) {throw new LangfuseNotFoundError(- `Observation with id ${this.event.id} not found`+ `Observation with id ${this.event.id} not found`,);}@@ -126,7 +152,7 @@ export class ObservationProcessor implements EventProcessor {this.event.body,this.calculateTokenDelegate,internalModel ?? undefined,- existingObservation ?? undefined+ existingObservation ?? undefined,): [undefined, undefined];@@ -162,7 +188,7 @@ export class ObservationProcessor implements EventProcessor {const calculatedCosts = ObservationProcessor.calculateTokenCosts(internalModel,userProvidedTokenCosts,- tokenCounts+ tokenCounts,);// merge metadata from existingObservation.metadata and metadata@@ -170,7 +196,7 @@ export class ObservationProcessor implements EventProcessor {existingObservation?.metadata? jsonSchema.parse(existingObservation.metadata): undefined,- this.event.body.metadata ?? undefined+ this.event.body.metadata ?? undefined,);const prompt =@@ -323,7 +349,7 @@ export class ObservationProcessor implements EventProcessor {text: unknown;}) => number | undefined,model?: Model,- existingObservation?: Omit<Observation, "input" | "output">+ existingObservation?: Omit<Observation, "input" | "output">,) {let newPromptTokens = body.usage?.input;if (newPromptTokens === undefined && model && model.tokenizerId) {@@ -334,7 +360,7 @@ export class ObservationProcessor implements EventProcessor {});} else {logger.info(- `No input provided, trying to calculate for id: ${existingObservation?.id}`+ `No input provided, trying to calculate for id: ${existingObservation?.id}`,);const observationInput = await prisma.observation.findFirst({where: { id: existingObservation?.id, projectId: projectId },@@ -360,7 +386,7 @@ export class ObservationProcessor implements EventProcessor {});} else {logger.info(- `No output provided, trying to calculate for id: ${existingObservation?.id}`+ `No output provided, trying to calculate for id: ${existingObservation?.id}`,);const observationOutput = await prisma.observation.findFirst({where: { id: existingObservation?.id, projectId: projectId },@@ -385,7 +411,7 @@ export class ObservationProcessor implements EventProcessor {outputCost?: Decimal | null;totalCost?: Decimal | null;},- tokenCounts: { input?: number; output?: number; total?: number }+ tokenCounts: { input?: number; output?: number; total?: number },): {inputCost?: Decimal | null;outputCost?: Decimal | null;@@ -402,7 +428,7 @@ export class ObservationProcessor implements EventProcessor {totalCost:userProvidedCosts.totalCost ??(userProvidedCosts.inputCost ?? new Decimal(0)).add(- userProvidedCosts.outputCost ?? new Decimal(0)+ userProvidedCosts.outputCost ?? new Decimal(0),),};}@@ -488,7 +514,7 @@ export class ObservationProcessor implements EventProcessor {existingObservation.projectId !== apiScope.projectId) {throw new ForbiddenError(- `Access denied for observation creation ${existingObservation.projectId} `+ `Access denied for observation creation ${existingObservation.projectId} `,);}@@ -505,6 +531,7 @@ export class ObservationProcessor implements EventProcessor {});}}+export class TraceProcessor implements EventProcessor {event: z.infer<typeof traceEvent>;@@ -518,7 +545,7 @@ export class TraceProcessor implements EventProcessor {}async process(- apiScope: LegacyIngestionAccessScope+ apiScope: LegacyIngestionAccessScope,): Promise<Trace | Observation | Score> {const { body } = this.event;@@ -527,7 +554,7 @@ export class TraceProcessor implements EventProcessor {const internalId = body.id ?? v4();logger.debug(- `Trying to create trace, project ${apiScope.projectId}, id: ${internalId}`+ `Trying to create trace, project ${apiScope.projectId}, id: ${internalId}`,);const existingTrace = await prisma.trace.findFirst({@@ -538,7 +565,7 @@ export class TraceProcessor implements EventProcessor {if (existingTrace && existingTrace.projectId !== apiScope.projectId) {throw new ForbiddenError(- `Access denied for trace creation ${existingTrace.projectId}`+ `Access denied for trace creation ${existingTrace.projectId}`,);}@@ -546,7 +573,7 @@ export class TraceProcessor implements EventProcessor {existingTrace?.metadata? jsonSchema.parse(existingTrace.metadata): undefined,- body.metadata ?? undefined+ body.metadata ?? undefined,);const mergedTags =@@ -614,6 +641,7 @@ export class TraceProcessor implements EventProcessor {return upsertedTrace;}}+export class ScoreProcessor implements EventProcessor {event: z.infer<typeof scoreEvent>;@@ -624,12 +652,12 @@ export class ScoreProcessor implements EventProcessor {auth(apiScope: LegacyIngestionAccessScope) {if (apiScope.accessLevel !== "scores" && apiScope.accessLevel !== "all")throw new ForbiddenError(- `Access denied for score creation, ${apiScope.accessLevel}`+ `Access denied for score creation, ${apiScope.accessLevel}`,);}async process(- apiScope: LegacyIngestionAccessScope+ apiScope: LegacyIngestionAccessScope,): Promise<Trace | Observation | Score> {const { body } = this.event;@@ -647,7 +675,7 @@ export class ScoreProcessor implements EventProcessor {});if (existingScore && existingScore.projectId !== apiScope.projectId) {throw new ForbiddenError(- `Access denied for score creation ${existingScore.projectId}`+ `Access denied for score creation ${existingScore.projectId}`,);}diff --git a/packages/shared/src/server/ingestion/legacy/index.ts b/packages/shared/src/server/ingestion/legacy/index.tsindex 55c3e3fb47..00253a2367 100644--- a/packages/shared/src/server/ingestion/legacy/index.ts+++ b/packages/shared/src/server/ingestion/legacy/index.ts@@ -2,14 +2,8 @@ import { env } from "node:process";import z from "zod";import { ForbiddenError, UnauthorizedError } from "../../../errors";import { eventTypes, ingestionApiSchema, ingestionEvent } from "../types";-import {- EventProcessor,- TraceProcessor,- ObservationProcessor,- ScoreProcessor,- SdkLogProcessor,-} from "./EventProcessor";-import { EventBodyType, EventName, TraceUpsertEventType } from "../../queues";+import { getProcessorForEvent } from "./EventProcessor";+import { TraceUpsertEventType } from "../../queues";import {convertTraceUpsertEventsToRedisEvents,getTraceUpsertQueue,@@ -144,40 +138,18 @@ const handleSingleEvent = async (const cleanedEvent = ingestionEvent.parse(cleanEvent(event));- const { type } = cleanedEvent;-- let processor: EventProcessor;- switch (type) {- case eventTypes.TRACE_CREATE:- processor = new TraceProcessor(cleanedEvent);- break;- 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:- processor = new ObservationProcessor(- cleanedEvent,- calculateTokenDelegate,- );- break;- case eventTypes.SCORE_CREATE: {- processor = new ScoreProcessor(cleanedEvent);- break;- }- case eventTypes.SDK_LOG:- processor = new SdkLogProcessor(cleanedEvent);- }-// Deny access to non-score events if the access level is not "all"// This is an additional safeguard to auth checks in EventProcessor- if (apiScope.accessLevel !== "all" && type !== eventTypes.SCORE_CREATE) {+ if (+ apiScope.accessLevel !== "all" &&+ cleanedEvent.type !== eventTypes.SCORE_CREATE+ ) {throw new ForbiddenError("Access denied. Event type not allowed.");}- return await processor.process(apiScope);+ return getProcessorForEvent(cleanedEvent, calculateTokenDelegate).process(+ apiScope,+ );};// cleans NULL characters from the event@@ -208,7 +180,7 @@ export const isNotNullOrUndefined = <T>(export const isUndefinedOrNull = <T>(val?: T | null): val is undefined | null =>val === undefined || val === null;-export const sendToWorkerIfEnvironmentConfigured = async (+export const addTracesToTraceUpsertQueue = async (batchResults: BatchResult[],projectId: string,): Promise<void> => {@@ -235,32 +207,6 @@ export const sendToWorkerIfEnvironmentConfigured = async (}await queue.addBulk(convertTraceUpsertEventsToRedisEvents(traceEvents));- } else if (- env.LANGFUSE_WORKER_HOST &&- env.LANGFUSE_WORKER_PASSWORD &&- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION- ) {- logger.info(`Sending ${traceEvents.length} events to worker via HTTP`);- const body: EventBodyType = {- name: EventName.TraceUpsert,- payload: traceEvents,- };-- if (traceEvents.length > 0) {- await fetch(`${env.LANGFUSE_WORKER_HOST}/api/events`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization:- "Basic " +- Buffer.from(- "admin" + ":" + env.LANGFUSE_WORKER_PASSWORD,- ).toString("base64"),- },- body: JSON.stringify(body),- signal: AbortSignal.timeout(8 * 1000),- });- }}} catch (error) {logger.error("Error sending events to worker", error);diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.tsindex 35d4f11707..ceb6ed1501 100644--- a/packages/shared/src/server/ingestion/types.ts+++ b/packages/shared/src/server/ingestion/types.ts@@ -115,7 +115,7 @@ export const CreateGenerationBody = CreateSpanBody.extend({z.array(z.string()),z.record(z.string()),])- .nullish()+ .nullish(),).nullish(),usage: usage,@@ -143,7 +143,7 @@ export const UpdateGenerationBody = UpdateSpanBody.extend({z.array(z.string()),z.record(z.string()),])- .nullish()+ .nullish(),).nullish(),usage: usage,@@ -174,14 +174,14 @@ export const ScoreBody = z.discriminatedUnion("dataType", [value: z.number(),dataType: z.literal("NUMERIC"),configId: z.string().nullish(),- })+ }),),BaseScoreBody.merge(z.object({value: z.string(),dataType: z.literal("CATEGORICAL"),configId: z.string().nullish(),- })+ }),),BaseScoreBody.merge(z.object({@@ -191,14 +191,14 @@ export const ScoreBody = z.discriminatedUnion("dataType", [}),dataType: z.literal("BOOLEAN"),configId: z.string().nullish(),- })+ }),),BaseScoreBody.merge(z.object({value: z.union([z.string(), z.number()]),dataType: z.undefined(),configId: z.string().nullish(),- })+ }),),]);@@ -243,7 +243,7 @@ export const LegacyGenerationsCreateSchema = z.object({modelParameters: z.record(z.string(),- z.union([z.string(), z.number(), z.boolean()]).nullish()+ z.union([z.string(), z.number(), z.boolean()]).nullish(),).nullish(),prompt: jsonSchema.nullish(),@@ -267,7 +267,7 @@ export const LegacyGenerationPatchSchema = z.object({modelParameters: z.record(z.string(),- z.union([z.string(), z.number(), z.boolean()]).nullish()+ z.union([z.string(), z.number(), z.boolean()]).nullish(),).nullish(),prompt: jsonSchema.nullish(),@@ -291,7 +291,7 @@ export const LegacyObservationBody = z.object({modelParameters: z.record(z.string(),- z.union([z.string(), z.number(), z.boolean()]).nullish()+ z.union([z.string(), z.number(), z.boolean()]).nullish(),).nullish(),input: jsonSchema.nullish(),@@ -306,6 +306,7 @@ export const LegacyObservationBody = z.object({export const SdkLogEvent = z.object({log: jsonSchema,+ id: z.string().nullish(), // Not used, but makes downstream processing easier.});// definitions for the ingestion API@@ -402,7 +403,7 @@ export const ingestionBatchEvent = z.array(ingestionEvent);export type IngestionBatchEventType = z.infer<typeof ingestionBatchEvent>;export const ingestionEventWithProjectId = ingestionEvent.and(- z.object({ projectId: z.string() })+ z.object({ projectId: z.string() }),);export type IngestionEventWithProjectIdType = z.infer<typeof ingestionEventWithProjectIddiff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 52ca50b5fd..62862597d6 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -1,5 +1,5 @@import { z } from "zod";-import { ingestionBatchEvent, TCarrier } from ".";+import { eventTypes, ingestionBatchEvent, TCarrier } from ".";export enum EventName {TraceUpsert = "TraceUpsert",@@ -9,7 +9,8 @@ export enum EventName {CloudUsageMetering = "CloudUsageMetering",}-export const LegacyIngestionEvent = z.object({+export const LegacyIngestionEventFull = z.object({+ useS3EventStore: z.literal(false),data: ingestionBatchEvent,authCheck: z.object({validKey: z.literal(true),@@ -20,6 +21,29 @@ export const LegacyIngestionEvent = z.object({}),});+export const LegacyIngestionEventMeta = z.object({+ useS3EventStore: z.literal(true),+ data: z.array(+ z.object({+ type: z.nativeEnum(eventTypes),+ eventBodyId: z.string(),+ eventId: z.string(),+ }),+ ),+ authCheck: z.object({+ validKey: z.literal(true),+ scope: z.object({+ projectId: z.string(),+ accessLevel: z.enum(["all", "scores"]),+ }),+ }),+});++export const LegacyIngestionEvent = z.discriminatedUnion("useS3EventStore", [+ LegacyIngestionEventFull,+ LegacyIngestionEventMeta,+]);+export const BatchExportJobSchema = z.object({projectId: z.string(),batchExportId: z.string(),diff --git a/packages/shared/src/server/services/S3StorageService.ts b/packages/shared/src/server/services/S3StorageService.tsindex c16030c6c9..bf7dfb9c93 100644--- a/packages/shared/src/server/services/S3StorageService.ts+++ b/packages/shared/src/server/services/S3StorageService.ts@@ -25,11 +25,10 @@ export class S3StorageService {bucketName: string;endpoint: string | undefined;region: string | undefined;+ forcePathStyle: boolean;}) {- const { accessKeyId, secretAccessKey, bucketName, endpoint, region } =- params;-// Use accessKeyId and secretAccessKey if provided or fallback to default credentials+ const { accessKeyId, secretAccessKey } = params;const credentials =accessKeyId !== undefined && secretAccessKey !== undefined? {@@ -40,10 +39,11 @@ export class S3StorageService {this.client = new S3Client({credentials,- endpoint,- region,+ endpoint: params.endpoint,+ region: params.region,+ forcePathStyle: params.forcePathStyle,});- this.bucketName = bucketName;+ this.bucketName = params.bucketName;}public async uploadFile({@@ -72,7 +72,7 @@ export class S3StorageService {}}- public async uploadJson(path: string, body: Record<string, unknown>) {+ public async uploadJson(path: string, body: Record<string, unknown>[]) {const putCommand = new PutObjectCommand({Bucket: this.bucketName,Key: path,@@ -88,6 +88,21 @@ export class S3StorageService {}}+ public async download(path: string): Promise<string> {+ const getCommand = new GetObjectCommand({+ Bucket: this.bucketName,+ Key: path,+ });++ try {+ const response = await this.client.send(getCommand);+ return (await response.Body?.transformToString()) ?? "";+ } catch (err) {+ logger.error(`Failed to download file from S3 ${path}`, err);+ throw Error("Failed to download file from S3");+ }+ }+private async getSignedUrl(fileName: string,ttlSeconds: number,diff --git a/web/src/__tests__/generation-exports.servertest.ts b/web/src/__tests__/generation-exports.servertest.tsindex c4b27579e5..030b8a588b 100644--- a/web/src/__tests__/generation-exports.servertest.ts+++ b/web/src/__tests__/generation-exports.servertest.ts@@ -14,7 +14,7 @@ describe("observations.export RPC", () => {beforeAll(async () => {// Disable S3 upload- process.env.S3_ENDPOINT = "";+ process.env.S3_BUCKET_NAME = "";await pruneDatabase();const traceId = "trace-1";diff --git a/web/src/env.mjs b/web/src/env.mjsindex 1668676c81..52de73b352 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -107,6 +107,7 @@ export const env = createEnv({S3_SECRET_ACCESS_KEY: z.string().optional(),S3_BUCKET_NAME: z.string().optional(),S3_REGION: z.string().optional(),+ S3_FORCE_PATH_STYLE: z.enum(["true", "false"]).default("false"),// Database exportsDB_EXPORT_PAGE_SIZE: z.number().optional(),// Worker@@ -170,6 +171,9 @@ export const env = createEnv({LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: z.string().optional(),LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: z.string().optional(),LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: z.string().optional(),+ LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: z+ .enum(["true", "false"])+ .default("false"),LANGFUSE_ASYNC_INGESTION_PROCESSING: z.enum(["true", "false"]).default("false"),@@ -363,6 +367,7 @@ export const env = createEnv({S3_SECRET_ACCESS_KEY: process.env.S3_SECRET_ACCESS_KEY,S3_BUCKET_NAME: process.env.S3_BUCKET_NAME,S3_REGION: process.env.S3_REGION,+ S3_FORCE_PATH_STYLE: process.env.S3_FORCE_PATH_STYLE,// S3 event uploadLANGFUSE_S3_EVENT_UPLOAD_ENABLED:process.env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED,@@ -378,6 +383,8 @@ export const env = createEnv({process.env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY:process.env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,+ LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE:+ process.env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE,// Database exportsDB_EXPORT_PAGE_SIZE: process.env.DB_EXPORT_PAGE_SIZE,// Workerdiff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 495cf6f40c..543c15d58f 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -8,21 +8,16 @@ import {traceException,redis,logger,- type AuthHeaderValidVerificationResult,- type ingestionBatchEvent,handleBatch,recordIncrement,getCurrentSpan,LegacyIngestionQueue,S3StorageService,instrumentAsync,-} from "@langfuse/shared/src/server";-import {- SdkLogProcessor,- type EventProcessor,- ObservationProcessor,- ScoreProcessor,- TraceProcessor,+ getProcessorForEvent,+ type AuthHeaderValidVerificationResult,+ type LegacyIngestionEventType,+ type IngestionEventType,} from "@langfuse/shared/src/server";import { telemetry } from "@/src/features/telemetry";import { jsonSchema } from "@langfuse/shared";@@ -35,7 +30,7 @@ import {UnauthorizedError,} from "@langfuse/shared";import {- sendToWorkerIfEnvironmentConfigured,+ addTracesToTraceUpsertQueue,QueueJobs,instrumentSync,} from "@langfuse/shared/src/server";@@ -53,11 +48,46 @@ export const config = {},};+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;+};++/**+ * This handler performs multiple actions to ingest data. It is compatible with the new async workflow, but also+ * supports the old synchronous workflow which processes events in the web container.+ * Overall, the processing of each incoming request happens in three stages+ * 1. Validation+ * - Check that the user has permissions+ * - Check whether rate-limits are breached+ * - Check that the request is well-formed+ * 2. Async Processing+ * - Upload each event to S3 for long-term storage and as an event cache+ * - Add the event batch to the queue for async processing+ * - Fallback to sync processing on errors+ * 3. Sync Processing+ * @param req+ * @param res+ */export default async function handler(req: NextApiRequest,res: NextApiResponse,) {try {+ /**************+ * VALIDATION *+ **************/await runMiddleware(req, res, cors);if (req.method !== "POST") throw new MethodNotAllowedError();@@ -124,6 +154,7 @@ export default async function handler(}const validationErrors: { id: string; error: unknown }[] = [];+ const authenticationErrors: { id: string; error: unknown }[] = [];const batch: z.infer<typeof ingestionEvent>[] = parsedSchema.data.batch.flatMap((event) => {@@ -149,6 +180,13 @@ export default async function handler(});return [];}+ if (!isAuthorized(parsed.data, authCheck)) {+ authenticationErrors.push({+ id: parsed.data.id,+ error: new UnauthorizedError("Access Scope Denied"),+ });+ return [];+ }return [parsed.data];}).flatMap((event) => {@@ -164,57 +202,71 @@ export default async function handler(const sortedBatch = sortBatch(batch);+ /********************+ * ASYNC PROCESSING *+ ********************/+ let s3UploadErrored = false;if (env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true") {await instrumentAsync({ name: "s3-upload-events" }, async () => {if (env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET === undefined) {- logger.warn(- "S3 event upload activated, but no bucket configured. Skipping upload.",- );- } else {- const s3Client = new S3StorageService({- accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,- secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,- bucketName: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,- endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,- region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,- });- const results = await Promise.allSettled(- sortedBatch.map(async (event) => {- const eventName = event.type.split("-").shift();- return event.type !== eventTypes.SDK_LOG- ? s3Client.uploadJson(- `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${authCheck.scope.projectId}/${eventName}/${event.body.id}/${event.id}.json`,- event,- )- : Promise.resolve();- }),- );- results.forEach((result) => {- if (result.status === "rejected") {- logger.error("Failed to upload event to S3", {- error: result.reason,- });- }- });+ throw new Error("S3 event store is enabled but no bucket is set");}+ const s3Client = getS3StorageServiceClient(+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ );+ // S3 Event Upload is currently blocking, but non-failing.+ // If a promise rejects, we log it below, but do not throw an error.+ // In this case, we upload the full batch into the Redis queue.+ const results = await Promise.allSettled(+ sortedBatch.map(async (event) => {+ const eventName = event.type.split("-").shift();+ // We upload the event in an array to the S3 bucket.+ // This should allow us to eventually batch events together and increase cost-efficiency through+ // reduced write operations.+ return event.type !== eventTypes.SDK_LOG+ ? s3Client.uploadJson(+ `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${authCheck.scope.projectId}/${eventName}/${event.body.id}/${event.id}.json`,+ [event],+ )+ : Promise.resolve();+ }),+ );+ results.forEach((result) => {+ if (result.status === "rejected") {+ s3UploadErrored = true;+ logger.error("Failed to upload event to S3", {+ 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) {- // this function MUST NOT return but send the HTTP response directlyconst queue = LegacyIngestionQueue.getInstance();if (queue) {- // still need to check auth scope for all events individually+ let addToQueueFailed = false;- const failedAccessScope = accessCheckPerEvent(sortedBatch, authCheck);+ const queuePayload: LegacyIngestionEventType =+ env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true" && !s3UploadErrored+ ? {+ data: sortedBatch.map((event) => ({+ type: event.type,+ eventBodyId: event.body.id ?? "",+ eventId: event.id,+ })),+ authCheck,+ useS3EventStore: true,+ }+ : { data: sortedBatch, authCheck, useS3EventStore: false };- let addToQueueFailed = false;try {await queue.add(QueueJobs.LegacyIngestionJob,{- payload: { data: sortedBatch, authCheck: authCheck },+ payload: queuePayload,id: randomUUID(),timestamp: new Date(),name: QueueJobs.LegacyIngestionJob as const,@@ -239,13 +291,8 @@ export default async function handler(if (!addToQueueFailed) {return handleBatchResult(- [- ...validationErrors,- ...failedAccessScope.map((e) => ({- id: e.id,- error: "Access Scope Denied",- })),- ], // we are not sending additional server errors to the client in case of early return+ // we are not sending additional server errors to the client in case of early return+ [...validationErrors, ...authenticationErrors],sortedBatch.map((event) => ({ id: event.id, result: event })),res,);@@ -257,17 +304,20 @@ export default async function handler(}}+ /*******************+ * SYNC PROCESSING *+ *******************/const result = await handleBatch(sortedBatch, authCheck, tokenCount);// send out REST requests to worker for all trace types- await sendToWorkerIfEnvironmentConfigured(+ await addTracesToTraceUpsertQueue(result.results,authCheck.scope.projectId,);// in case we did not return early, we return the result herehandleBatchResult(- [...validationErrors, ...result.errors],+ [...validationErrors, ...authenticationErrors, ...result.errors],result.results,res,);@@ -306,41 +356,16 @@ export default async function handler(}}-const accessCheckPerEvent = (- events: z.infer<typeof ingestionBatchEvent>,- authCheck: AuthHeaderValidVerificationResult,-) => {- const unauthorizedEvents: { id: string; type: string }[] = [];-- for (const event of events) {- try {- let processor: EventProcessor;- switch (event.type) {- case eventTypes.TRACE_CREATE:- processor = new TraceProcessor(event);- break;- 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:- processor = new ObservationProcessor(event, tokenCount);- break;- case eventTypes.SCORE_CREATE:- processor = new ScoreProcessor(event);- break;- case eventTypes.SDK_LOG:- processor = new SdkLogProcessor(event);- break;- }- processor.auth(authCheck.scope);- } catch (error) {- unauthorizedEvents.push({ id: event.id, type: event.type });- }+const isAuthorized = (+ event: IngestionEventType,+ authScope: AuthHeaderValidVerificationResult,+): boolean => {+ try {+ getProcessorForEvent(event, tokenCount).auth(authScope.scope);+ return true;+ } catch (error) {+ return false;}- return unauthorizedEvents;};/**diff --git a/web/src/server/api/routers/generations/exportQuery/index.ts b/web/src/server/api/routers/generations/exportQuery/index.tsindex eaa43e66e5..4bc8476198 100644--- a/web/src/server/api/routers/generations/exportQuery/index.ts+++ b/web/src/server/api/routers/generations/exportQuery/index.ts@@ -67,21 +67,17 @@ export const generationsExportQuery = protectedProjectProcedureconst fileExtension = exportOptions[input.fileFormat].extension;const fileName = `lf-export-${input.projectId}-${fileDate}.${fileExtension}`;- const accessKeyId = env.S3_ACCESS_KEY_ID;- const secretAccessKey = env.S3_SECRET_ACCESS_KEY;- const bucketName = env.S3_BUCKET_NAME;- const endpoint = env.S3_ENDPOINT;- const region = env.S3_REGION;-// If bucketName is configured, we expect that the user has some valid S3 setup.+ const bucketName = env.S3_BUCKET_NAME;if (bucketName) {logger.info(`Preparing export for ${fileName} on S3`);const { signedUrl } = await new S3StorageService({- accessKeyId,- secretAccessKey,+ accessKeyId: env.S3_ACCESS_KEY_ID,+ secretAccessKey: env.S3_SECRET_ACCESS_KEY,bucketName,- endpoint,- region,+ endpoint: env.S3_ENDPOINT,+ region: env.S3_REGION,+ forcePathStyle: env.S3_FORCE_PATH_STYLE === "true",}).uploadFile({fileName,fileType: exportOptions[input.fileFormat].fileType,diff --git a/worker/src/env.ts b/worker/src/env.tsindex be56edcc57..90e5ba94b2 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -19,6 +19,17 @@ const EnvSchema = z.object({S3_BUCKET_NAME: z.string().optional(),S3_ENDPOINT: z.string().optional(),S3_REGION: z.string().optional(),+ S3_FORCE_PATH_STYLE: z.enum(["true", "false"]).default("false"),+ LANGFUSE_S3_EVENT_UPLOAD_ENABLED: z.enum(["true", "false"]).default("false"),+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: z.string().optional(),+ LANGFUSE_S3_EVENT_UPLOAD_PREFIX: z.string().default(""),+ LANGFUSE_S3_EVENT_UPLOAD_REGION: z.string().optional(),+ LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: z.string().optional(),+ LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: z.string().optional(),+ LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: z.string().optional(),+ LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: z+ .enum(["true", "false"])+ .default("false"),BATCH_EXPORT_ROW_LIMIT: z.coerce.number().positive().default(50_000),BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS: z.coerce.number()diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.tsindex a0d40d49d9..e60b4ebada 100644--- a/worker/src/features/batchExport/handleBatchExportJob.ts+++ b/worker/src/features/batchExport/handleBatchExportJob.ts@@ -320,17 +320,6 @@ export const handleBatchExportJob = async (},);- // Stream upload results to S3- const accessKeyId = env.S3_ACCESS_KEY_ID;- const secretAccessKey = env.S3_SECRET_ACCESS_KEY;- const bucketName = env.S3_BUCKET_NAME;- const endpoint = env.S3_ENDPOINT;- const region = env.S3_REGION;-- if (!bucketName) {- throw new Error("No S3 bucket configured for exports.");- }-const fileDate = new Date().toISOString();const fileExtension =exportOptions[jobDetails.format as BatchExportFileFormat].extension;@@ -338,12 +327,19 @@ export const handleBatchExportJob = async (const expiresInSeconds =env.BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS * 3600;+ // Stream upload results to S3+ const bucketName = env.S3_BUCKET_NAME;+ if (!bucketName) {+ throw new Error("No S3 bucket configured for exports.");+ }+const { signedUrl } = await new S3StorageService({- accessKeyId,- secretAccessKey,+ accessKeyId: env.S3_ACCESS_KEY_ID,+ secretAccessKey: env.S3_SECRET_ACCESS_KEY,bucketName,- endpoint,- region,+ endpoint: env.S3_ENDPOINT,+ region: env.S3_REGION,+ forcePathStyle: env.S3_FORCE_PATH_STYLE === "true",}).uploadFile({fileName,fileType:diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.tsindex 45e06b2257..38bb1ab221 100644--- a/worker/src/queues/legacyIngestionQueue.ts+++ b/worker/src/queues/legacyIngestionQueue.ts@@ -8,21 +8,87 @@ import {recordHistogram,TQueueJobTypes,logger,+ IngestionEventType,+ S3StorageService,+ ingestionBatchEvent,+ ingestionEvent,} from "@langfuse/shared/src/server";import {handleBatch,- sendToWorkerIfEnvironmentConfigured,+ addTracesToTraceUpsertQueue,} from "@langfuse/shared/src/server";import { tokenCount } from "../features/tokenisation/usage";+import { env } from "../env";++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 legacyIngestionQueueProcessor: Processor = async (job: Job<TQueueJobTypes[QueueName.LegacyIngestionQueue]>,) => {try {const startTime = Date.now();++ let ingestionEvents: IngestionEventType[] = [];+ if (job.data.payload.useS3EventStore) {+ 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",+ );+ }+ // If we used the S3 store we need to fetch the ingestionEvents from S3+ const s3Client = getS3StorageServiceClient(+ 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`,+ );+ const parsedFile = JSON.parse(file);+ const parsed = ingestionBatchEvent.safeParse(parsedFile);+ if (parsed.success) {+ return parsed.data;+ } else {+ // Fallback to non-array format for backwards compatibility+ 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();+ } else {+ // If we didn't use the S3 store we can consume the ingestionEvents directly from Redis+ ingestionEvents = job.data.payload.data;+ }+logger.info("Processing legacy ingestion", {- payload: job.data.payload.data.map(({ body, ...rest }) => {+ payload: ingestionEvents.map(({ body, ...rest }) => {let modifiedBody = body;if (body && "input" in modifiedBody) {// eslint-disable-next-line @typescript-eslint/no-unused-vars@@ -48,13 +114,13 @@ export const legacyIngestionQueueProcessor: Processor = async (});const result = await handleBatch(- job.data.payload.data,+ ingestionEvents,job.data.payload.authCheck,tokenCount,);// send out REDIS requests to worker for all trace types- await sendToWorkerIfEnvironmentConfigured(+ await addTracesToTraceUpsertQueue(result.results,job.data.payload.authCheck.scope.projectId,);