🪢 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: skip S3 list and legacy trace insert based on env flag (#8298)
Steffen Schmitzaa4d34ae6681
diff --git a/worker/src/env.ts b/worker/src/env.tsindex 6188f42505..6cf2899f4e 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -242,6 +242,9 @@ const EnvSchema = z.object({.positive().default(120_000), // 2 minutes+ LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE: z+ .enum(["true", "false"])+ .default("true"),LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES: z.enum(["true", "false"]).default("false"),diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsindex 4bcb889715..b58b137e28 100644--- a/worker/src/queues/ingestionQueue.ts+++ b/worker/src/queues/ingestionQueue.ts@@ -138,10 +138,12 @@ export const ingestionQueueProcessorBuilder = (const events: IngestionEventType[] = [];// Check if we should skip S3 list operation- // The producer sets skipS3List to true if it's an OTel observationconst shouldSkipS3List =- job.data.payload.data.skipS3List && job.data.payload.data.fileKey;-+ // The producer sets skipS3List to true if it's an OTel observation+ (job.data.payload.data.skipS3List && job.data.payload.data.fileKey) ||+ // If we do not insert into the traces table, we can skip the list and process single files+ (env.LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE === "false" &&+ clickhouseEntityType === "trace");const s3Prefix = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${clickhouseEntityType}/${job.data.payload.data.eventBodyId}/`;let totalS3DownloadSizeBytes = 0;diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex e40ed286ab..7453f5cc41 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -371,59 +371,85 @@ export class IngestionService {traceEventList: timeSortedEvents,});- const minTimestamp = Math.min(- ...timeSortedEvents.flatMap((e) =>- e.body?.timestamp ? [new Date(e.body.timestamp).getTime()] : [],+ // Search for the first non-null input and output in the trace events and set them on the merged result.+ // Fallback to the ClickHouse input/output if none are found within the events list.+ const reversedRawRecords = timeSortedEvents.slice().reverse();+ const finalIO = {+ input: this.stringify(+ reversedRawRecords.find((record) => record?.body?.input)?.body?.input,),- );- const timestamp =- minTimestamp === Infinity- ? undefined- : convertDateToClickhouseDateTime(new Date(minTimestamp));- const clickhouseTraceRecord = await this.getClickhouseRecord({- projectId,- entityId,- table: TableName.Traces,- additionalFilters: {- whereCondition: timestamp- ? " AND timestamp >= {timestamp: DateTime64(3)} "- : "",- params: { timestamp },- },- });+ output: this.stringify(+ reversedRawRecords.find((record) => record?.body?.output)?.body?.output,+ ),+ };- if (clickhouseTraceRecord) {- recordIncrement("langfuse.ingestion.lookup.hit", 1, {- store: "clickhouse",- object: "trace",+ if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE === "true") {+ const minTimestamp = Math.min(+ ...timeSortedEvents.flatMap((e) =>+ e.body?.timestamp ? [new Date(e.body.timestamp).getTime()] : [],+ ),+ );+ const timestamp =+ minTimestamp === Infinity+ ? undefined+ : convertDateToClickhouseDateTime(new Date(minTimestamp));+ const clickhouseTraceRecord = await this.getClickhouseRecord({+ projectId,+ entityId,+ table: TableName.Traces,+ additionalFilters: {+ whereCondition: timestamp+ ? " AND timestamp >= {timestamp: DateTime64(3)} "+ : "",+ params: { timestamp },+ },});- }- const finalTraceRecord = await this.mergeTraceRecords({- clickhouseTraceRecord,- traceRecords,- });- finalTraceRecord.created_at =- clickhouseTraceRecord?.created_at ?? createdAtTimestamp.getTime();+ if (clickhouseTraceRecord) {+ recordIncrement("langfuse.ingestion.lookup.hit", 1, {+ store: "clickhouse",+ object: "trace",+ });+ }- // Search for the first non-null input and output in the trace events and set them on the merged result.- // Fallback to the ClickHouse input/output if none are found within the events list.- const reversedRawRecords = timeSortedEvents.slice().reverse();- finalTraceRecord.input = this.stringify(- reversedRawRecords.find((record) => record?.body?.input)?.body?.input ??- clickhouseTraceRecord?.input,- );- finalTraceRecord.output = this.stringify(- reversedRawRecords.find((record) => record?.body?.output)?.body?.output ??- clickhouseTraceRecord?.output,- );+ const finalTraceRecord = await this.mergeTraceRecords({+ clickhouseTraceRecord,+ traceRecords,+ });+ finalTraceRecord.created_at =+ clickhouseTraceRecord?.created_at ?? createdAtTimestamp.getTime();++ finalTraceRecord.input = finalIO.input ?? clickhouseTraceRecord?.input;+ finalTraceRecord.output = finalIO.output ?? clickhouseTraceRecord?.output;++ this.clickHouseWriter.addToQueue(TableName.Traces, finalTraceRecord);+ }++ // Experimental: Also write to traces_null table if experiment flag is enabled+ // Here we use the raw events to ensure that we stop relying on the merge logic+ if (+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true"+ ) {+ traceRecords.map(convertTraceToTraceNull).forEach((r) =>+ this.clickHouseWriter.addToQueue(TableName.TracesNull, {+ ...r,+ // We need to re-add input and output here as they were excluded in a previous mapping step+ input: finalIO.input ?? "",+ output: finalIO.output ?? "",+ }),+ );+ }// If the trace has a sessionId, we upsert the corresponding session into Postgres.- if (finalTraceRecord.session_id) {+ const traceRecordWithSession = traceRecords+ .slice()+ .reverse()+ .find((t) => t.session_id);+ if (traceRecordWithSession) {try {await this.prisma.$executeRaw`INSERT INTO trace_sessions (id, project_id, environment, created_at, updated_at)- VALUES (${finalTraceRecord.session_id}, ${projectId}, ${finalTraceRecord.environment}, NOW(), NOW())+ VALUES (${traceRecordWithSession.session_id}, ${projectId}, ${traceRecordWithSession.environment}, NOW(), NOW())ON CONFLICT (id, project_id)DO UPDATE SETenvironment = EXCLUDED.environment,@@ -432,30 +458,13 @@ export class IngestionService {`;} catch (e) {logger.error(- `Failed to upsert session ${finalTraceRecord.session_id}`,+ `Failed to upsert session ${traceRecordWithSession.session_id}`,e,);throw e;}}- this.clickHouseWriter.addToQueue(TableName.Traces, finalTraceRecord);-- // Experimental: Also write to traces_null table if experiment flag is enabled- // Here we use the raw events to ensure that we stop relying on the merge logic- if (- env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true"- ) {- traceRecords.map(convertTraceToTraceNull).forEach((r) =>- this.clickHouseWriter.addToQueue(TableName.TracesNull, {- ...r,- // We need to re-add input and output here as they were excluded in a previous mapping step- input: finalTraceRecord.input ?? "",- output: finalTraceRecord.output ?? "",- }),- );- }-// Add trace into trace upsert queue for eval processingconst traceUpsertQueue = TraceUpsertQueue.getInstance();if (!traceUpsertQueue) {@@ -464,8 +473,8 @@ export class IngestionService {}await traceUpsertQueue.add(QueueJobs.TraceUpsert, {payload: {- projectId: finalTraceRecord.project_id,- traceId: finalTraceRecord.id,+ projectId,+ traceId: entityId,},id: randomUUID(),timestamp: new Date(),