🪢 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: ingest otel events into new events table (dev) (#9548)
Steffen Schmitzcf40ce5093c8
diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex f657d15b97..54b98f58ff 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -98,7 +98,7 @@ CREATE TABLE IF NOT EXISTS eventslevel LowCardinality(String),status_message String, -- Threat '' and null the same for search- completion_start_time Nullable(DateTime64(3)),+ completion_start_time Nullable(DateTime64(6)),-- Promptprompt_id Nullable(String),@@ -152,8 +152,8 @@ CREATE TABLE IF NOT EXISTS eventsblob_storage_file_path String,event_raw String,event_bytes UInt64,- created_at DateTime64(3) DEFAULT now(),- updated_at DateTime64(3) DEFAULT now(),+ created_at DateTime64(6) DEFAULT now(),+ updated_at DateTime64(6) DEFAULT now(),event_ts DateTime64(6),is_deleted UInt8,diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex eb76f2a5c3..528b12cf7f 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -15,6 +15,7 @@ import {traceException,getS3EventStorageClient,QueueJobs,+ instrumentSync,} from "../";import { LangfuseOtelSpanAttributes } from "./attributes";@@ -160,6 +161,197 @@ export class OtelIngestionProcessor {: Promise.reject("Failed to instantiate otel ingestion queue");}+ /**+ * Processes incoming resourceSpans and produces an event base record that can be enriched+ * using the IngestionService.+ * @param resourceSpans+ */+ processToEvent(resourceSpans: ResourceSpan[]): any[] {+ return instrumentSync({ name: "otel-event-processor" }, (span) => {+ try {+ span.setAttribute("project_id", this.projectId);+ span.setAttribute(+ "total_span_count",+ this.getTotalSpanCount(resourceSpans),+ );++ // Input validation+ if (!Array.isArray(resourceSpans)) {+ return [];+ }+ if (resourceSpans.length === 0) {+ return [];+ }++ return resourceSpans+ .filter((r) => Boolean(r))+ .flatMap((resourceSpan) => {+ const resourceAttributes =+ this.extractResourceAttributes(resourceSpan);+ const events: any[] = [];++ for (const scopeSpan of resourceSpan?.scopeSpans ?? []) {+ const scopeAttributes = this.extractScopeAttributes(scopeSpan);+ for (const span of scopeSpan?.spans ?? []) {+ const spanAttributes = this.extractSpanAttributes(span);+ const traceId = this.parseId(span.traceId);+ const spanId = this.parseId(span.spanId);+ const parentSpanId = span?.parentSpanId+ ? this.parseId(span.parentSpanId)+ : null;+ const name = span.name;+ const startTimeISO =+ OtelIngestionProcessor.convertNanoTimestampToISO(+ span.startTimeUnixNano,+ );+ const endTimeISO =+ OtelIngestionProcessor.convertNanoTimestampToISO(+ span.endTimeUnixNano,+ );++ // Extract metadata from different sources+ const spanMetadata = this.extractMetadata(+ spanAttributes,+ "observation",+ );+ const traceMetadata = this.extractMetadata(+ spanAttributes,+ "trace",+ );++ // Construct metadata object with the specified structure+ const metadata = {+ // attributes: spanAttributes,+ resourceAttributes: resourceAttributes,+ scopeAttributes: scopeAttributes,+ ...spanMetadata,+ ...traceMetadata,+ };++ // Extract instrumentation metadata+ const serviceName = resourceAttributes?.["service.name"] as+ | string+ | undefined;+ const serviceVersion = resourceAttributes?.[+ "service.version"+ ] as string | undefined;+ const telemetrySdkLanguage = resourceAttributes?.[+ "telemetry.sdk.language"+ ] as string | undefined;+ const telemetrySdkName = resourceAttributes?.[+ "telemetry.sdk.name"+ ] as string | undefined;+ const telemetrySdkVersion = resourceAttributes?.[+ "telemetry.sdk.version"+ ] as string | undefined;+ const scopeName = scopeSpan?.scope?.name;+ const scopeVersion = scopeSpan?.scope?.version;++ events.push({+ projectId: this.projectId,+ traceId,+ spanId,+ parentSpanId,++ name,+ type: observationTypeMapper.mapToObservationType(+ spanAttributes,+ resourceAttributes,+ scopeSpan?.scope,+ ),+ environment: this.extractEnvironment(+ spanAttributes,+ resourceAttributes,+ ),+ version:+ spanAttributes?.[LangfuseOtelSpanAttributes.VERSION] ??+ resourceAttributes?.["service.version"] ??+ null,++ startTimeISO,+ endTimeISO,++ level:+ spanAttributes[+ LangfuseOtelSpanAttributes.OBSERVATION_LEVEL+ ] ??+ (span.status?.code === 2+ ? ObservationLevel.ERROR+ : ObservationLevel.DEFAULT),+ statusMessage:+ spanAttributes[+ LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE+ ] ??+ span.status?.message ??+ null,++ promptName:+ spanAttributes?.[+ LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME+ ] ??+ spanAttributes["langfuse.prompt.name"] ??+ this.parseLangfusePromptFromAISDK(spanAttributes)?.name ??+ null,+ promptVersion:+ spanAttributes?.[+ LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION+ ] ??+ spanAttributes["langfuse.prompt.version"] ??+ this.parseLangfusePromptFromAISDK(spanAttributes)+ ?.version ??+ null,++ modelParameters: this.extractModelParameters(+ spanAttributes,+ scopeSpan?.scope?.name ?? "",+ ),+ modelName: this.extractModelName(spanAttributes),+ completionStartTime: this.extractCompletionStartTime(+ spanAttributes,+ startTimeISO,+ ),++ // TODO: Usage details++ userId: this.extractUserId(spanAttributes),+ sessionId: this.extractSessionId(spanAttributes),++ ...this.extractInputAndOutput({+ events: span?.events ?? [],+ attributes: spanAttributes,+ instrumentationScopeName: scopeSpan?.scope?.name ?? "",+ }),++ // Metadata+ metadata,++ // Instrumentation metadata+ source: "otel",+ serviceName,+ serviceVersion,+ scopeName,+ scopeVersion,+ telemetrySdkLanguage,+ telemetrySdkName,+ telemetrySdkVersion,++ // Source data+ eventRaw: JSON.stringify(span),+ eventBytes: Buffer.byteLength(JSON.stringify(span), "utf8"),+ });+ }+ }++ return events;+ });+ } catch (error) {+ logger.error("Error processing OTEL spans to events:", error);+ traceException(error, span);+ throw error;+ }+ });+ }+/*** Process resource spans and convert them to Langfuse ingestion events.* Handles trace deduplication automatically using internal state.diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex f50c88b9ff..e6d91b44b4 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -507,3 +507,94 @@ export const convertPostgresScoreToInsert = (is_deleted: 0,};};++export const eventRecordBaseSchema = z.object({+ // Identifiers+ org_id: z.string().nullish(),+ project_id: z.string(),+ trace_id: z.string(),+ span_id: z.string(),+ // We mainly use the id for compatibility with old events that always had a `id` column.+ id: z.string(), // same as span_id. Needs to be set manually.+ parent_span_id: z.string().nullish(),++ // Core properties+ name: z.string(),+ type: z.string(),+ environment: z.string().default("default"),+ version: z.string().nullish(),++ user_id: z.string().nullish(),+ session_id: z.string().nullish(),++ level: z.string(),+ status_message: z.string().nullish(),++ // Prompt+ prompt_id: z.string().nullish(),+ prompt_name: z.string().nullish(),+ prompt_version: z.string().nullish(),++ // Model+ model_id: z.string().nullish(),+ provided_model_name: z.string().nullish(),+ model_parameters: z.string().nullish(),++ // Usage & Cost+ provided_usage_details: UsageCostSchema,+ usage_details: UsageCostSchema,+ provided_cost_details: UsageCostSchema,+ cost_details: UsageCostSchema,+ total_cost: z.number().nullish(),++ // I/O+ input: z.string().nullish(),+ output: z.string().nullish(),++ // Metadata - multiple approaches supported+ metadata: z.record(z.string(), z.string()),+ metadata_names: z.array(z.string()).default([]),+ metadata_values: z.array(z.any()).default([]),+ metadata_string_names: z.array(z.string()).default([]),+ metadata_string_values: z.array(z.string()).default([]),+ metadata_number_names: z.array(z.string()).default([]),+ metadata_number_values: z.array(z.number()).default([]),+ metadata_bool_names: z.array(z.string()).default([]),+ metadata_bool_values: z.array(z.number()).default([]),++ // Source metadata (Instrumentation)+ source: z.string(),+ service_name: z.string().nullish(),+ service_version: z.string().nullish(),+ scope_name: z.string().nullish(),+ scope_version: z.string().nullish(),+ telemetry_sdk_language: z.string().nullish(),+ telemetry_sdk_name: z.string().nullish(),+ telemetry_sdk_version: z.string().nullish(),++ // Generic props+ blob_storage_file_path: z.string(),+ event_raw: z.string(),+ event_bytes: z.number(),+ is_deleted: z.number(),+});++export const eventRecordReadSchema = eventRecordBaseSchema.extend({+ start_time: clickhouseStringDateSchema,+ end_time: clickhouseStringDateSchema.nullish(),+ completion_start_time: clickhouseStringDateSchema.nullish(),+ created_at: clickhouseStringDateSchema,+ updated_at: clickhouseStringDateSchema,+ event_ts: clickhouseStringDateSchema,+});+export type EventRecordReadType = z.infer<typeof eventRecordReadSchema>;++export const eventRecordInsertSchema = eventRecordBaseSchema.extend({+ start_time: z.number(),+ end_time: z.number().nullish(),+ completion_start_time: z.number().nullish(),+ created_at: z.number(),+ updated_at: z.number(),+ event_ts: z.number(),+});+export type EventRecordInsertType = z.infer<typeof eventRecordInsertSchema>;diff --git a/worker/src/env.ts b/worker/src/env.tsindex 383ed0477d..96a2e7aac2 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -272,9 +272,13 @@ const EnvSchema = z.object({.positive().default(120_000), // 2 minutes+ // Deprecated. Do not use!LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT: z.enum(["true", "false"]).default("false"),+ LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE: z+ .enum(["true", "false"])+ .default("false"),LANGFUSE_WEBHOOK_QUEUE_PROCESSING_CONCURRENCY: z.coerce.number()diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex 2165fb8474..25416fe495 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -70,8 +70,9 @@ export const otelIngestionQueueProcessor: Processor = async (projectId,publicKey,});+ const parsedSpans = JSON.parse(resourceSpans);const events: IngestionEventType[] =- await processor.processToIngestionEvents(JSON.parse(resourceSpans));+ await processor.processToIngestionEvents(parsedSpans);// Here, we split the events into observations and non-observations.// Observations go into the IngestionService directly whereas the non-observations make another run through the processEventBatch method.const traces = events.filter(@@ -136,6 +137,21 @@ export const otelIngestionQueueProcessor: Processor = async (),].flat(),);++ // If inserts into the events table are enabled, we run the dedicated processing for the otel+ // spans and move them into the dedicated IngestionService processor.+ if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true") {+ try {+ const events = processor.processToEvent(parsedSpans);+ await Promise.all(+ events.map((e) => ingestionService.writeEvent(e, fileKey)),+ );+ } catch (e) {+ traceException(e); // Mark span as errored+ logger.warn(`Failed to process events for ${projectId}: ${e}`, e);+ // Fallthrough while setting is experimental+ }+ }} catch (e) {if (e instanceof ForbiddenError) {traceException(e);diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex d38b6cb30b..45f9ad146d 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -11,6 +11,7 @@ import {TraceRecordInsertType,TraceNullRecordInsertType,DatasetRunItemRecordInsertType,+ EventRecordInsertType,} from "@langfuse/shared/src/server";import { env } from "../../env";@@ -44,6 +45,7 @@ export class ClickhouseWriter {[TableName.Observations]: [],[TableName.BlobStorageFileLog]: [],[TableName.DatasetRunItems]: [],+ [TableName.Events]: [],};this.start();@@ -111,6 +113,7 @@ export class ClickhouseWriter {this.flush(TableName.Observations, fullQueue),this.flush(TableName.BlobStorageFileLog, fullQueue),this.flush(TableName.DatasetRunItems, fullQueue),+ this.flush(TableName.Events, fullQueue),]).catch((err) => {logger.error("ClickhouseWriter.flushAll", err);});@@ -495,6 +498,7 @@ export enum TableName {Observations = "observations", // eslint-disable-line no-unused-varsBlobStorageFileLog = "blob_storage_file_log", // eslint-disable-line no-unused-varsDatasetRunItems = "dataset_run_items_rmt", // eslint-disable-line no-unused-vars+ Events = "events", // eslint-disable-line no-unused-vars}type RecordInsertType<T extends TableName> = T extends TableName.Scores@@ -509,7 +513,9 @@ type RecordInsertType<T extends TableName> = T extends TableName.Scores? BlobStorageFileLogInsertType: T extends TableName.DatasetRunItems? DatasetRunItemRecordInsertType- : never;+ : T extends TableName.Events+ ? EventRecordInsertType+ : never;type ClickhouseQueue = {[T in TableName]: ClickhouseWriterQueueItem<T>[];diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 640ccb601e..deda690465 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -39,6 +39,7 @@ import {findModel,validateAndInflateScore,DatasetRunItemRecordInsertType,+ EventRecordInsertType,hasNoJobConfigsCache,} from "@langfuse/shared/src/server";@@ -61,6 +62,79 @@ type InsertRecord =| ObservationRecordInsertType| DatasetRunItemRecordInsertType;+/**+ * Flexible input type for writing events to the events table.+ * This is intentionally loose to allow for iteration as the events+ * table schema evolves. Only required fields are enforced.+ */+export type EventInput = {+ // Required identifiers+ projectId: string;+ traceId: string;+ spanId: string;+ startTimeISO: string;++ // Optional identifiers+ orgId?: string;+ parentSpanId?: string;++ // Core properties+ name?: string;+ type?: string;+ environment?: string;+ version?: string;+ endTimeISO: string;+ completionStartTime?: string;++ // User/session+ userId?: string;+ sessionId?: string;+ level?: string;+ statusMessage?: string;++ // Prompt+ promptId?: string;+ promptName?: string;+ promptVersion?: string;++ // Model+ modelName?: string;+ modelParameters?: string;++ // Usage & Cost+ providedUsageDetails?: Record<string, number>;+ usageDetails?: Record<string, number>;+ providedCostDetails?: Record<string, number>;+ costDetails?: Record<string, number>;+ totalCost?: number;++ // I/O+ input?: string;+ output?: string;++ // Metadata+ // metadata can be a complex nested object with attributes, resourceAttributes, scopeAttributes, etc.+ metadata: Record<string, unknown>;++ // Source/instrumentation metadata+ source: string;+ serviceName?: string;+ serviceVersion?: string;+ scopeName?: string;+ scopeVersion?: string;+ telemetrySdkLanguage?: string;+ telemetrySdkName?: string;+ telemetrySdkVersion?: string;++ // Storage+ blobStorageFilePath?: string;+ eventRaw?: string;+ eventBytes?: number;++ // Catch-all for future fields+ [key: string]: any;+};+const immutableEntityKeys: {[TableName.Traces]: (keyof TraceRecordInsertType)[];[TableName.Scores]: (keyof ScoreRecordInsertType)[];@@ -169,6 +243,130 @@ export class IngestionService {}}+ /**+ * Writes a single event directly to the events table.+ * Unlike other ingestion methods, this does not perform merging since+ * events are immutable and written once.+ *+ * @param eventData - The event data to write+ * @param fileKey - The file key where the raw event data is stored+ */+ public async writeEvent(+ eventData: EventInput,+ fileKey: string,+ ): Promise<void> {+ logger.debug(+ `Writing event for project ${eventData.projectId} and span ${eventData.spanId}`,+ );++ const now = this.getNanosecondTimestamp();++ // Store the full metadata JSON+ const metadata = eventData.metadata;++ // Flatten to path-based arrays+ const flattened = this.flattenJsonToPathArrays(metadata);+ const metadataNames = flattened.names;+ const metadataValues = flattened.values;++ // Flatten to typed arrays+ const typed = this.flattenJsonToTypedPathArrays(metadata);+ const metadataStringNames = typed.stringNames;+ const metadataStringValues = typed.stringValues;+ const metadataNumberNames = typed.numberNames;+ const metadataNumberValues = typed.numberValues;+ const metadataBoolNames = typed.boolNames;+ const metadataBoolValues = typed.boolValues;++ const eventRecord: EventRecordInsertType = {+ // Required identifiers+ id: eventData.spanId,+ project_id: eventData.projectId,+ trace_id: eventData.traceId,+ span_id: eventData.spanId,++ // Optional identifiers+ parent_span_id: eventData.parentSpanId,++ // Core properties with defaults+ name: eventData.name ?? "",+ type: eventData.type ?? "SPAN",+ environment: eventData.environment ?? "default",+ version: eventData.version,++ // User/session+ user_id: eventData.userId,+ session_id: eventData.sessionId,++ // Status+ level: eventData.level ?? "DEFAULT",+ status_message: eventData.statusMessage,++ // Timestamps+ start_time: this.getNanosecondTimestamp(eventData.startTimeISO),+ end_time: this.getNanosecondTimestamp(eventData.endTimeISO),+ completion_start_time: eventData.completionStartTime+ ? this.getNanosecondTimestamp(eventData.completionStartTime)+ : null,++ // Prompt+ // prompt_id: eventData.promptId,+ prompt_name: eventData.promptName,+ prompt_version: eventData.promptVersion,++ // Model+ // model_id: eventData.modelId,+ provided_model_name: eventData.modelName,+ model_parameters: eventData.modelParameters,++ // Usage & Cost+ // provided_usage_details: eventData.providedUsageDetails ?? {},+ // usage_details: eventData.usageDetails ?? {},+ // provided_cost_details: eventData.providedCostDetails ?? {},+ // cost_details: eventData.costDetails ?? {},+ // total_cost: eventData.totalCost,++ // I/O+ input: eventData.input,+ output: eventData.output,++ // Metadata (multiple approaches)+ metadata,+ metadata_names: metadataNames,+ metadata_values: metadataValues,+ metadata_string_names: metadataStringNames,+ metadata_string_values: metadataStringValues,+ metadata_number_names: metadataNumberNames,+ metadata_number_values: metadataNumberValues,+ metadata_bool_names: metadataBoolNames,+ metadata_bool_values: metadataBoolValues,++ // Source/instrumentation metadata+ source: eventData.source,+ service_name: eventData.serviceName,+ service_version: eventData.serviceVersion,+ scope_name: eventData.scopeName,+ scope_version: eventData.scopeVersion,+ telemetry_sdk_language: eventData.telemetrySdkLanguage,+ telemetry_sdk_name: eventData.telemetrySdkName,+ telemetry_sdk_version: eventData.telemetrySdkVersion,++ // Storage+ blob_storage_file_path: fileKey,+ event_raw: eventData.eventRaw ?? "",+ event_bytes: eventData.eventBytes ?? 0,++ // System timestamps+ created_at: now,+ updated_at: now,+ event_ts: now,+ is_deleted: 0,+ } as any;++ // Write directly to ClickHouse queue (no merging for immutable events)+ this.clickHouseWriter.addToQueue(TableName.Events, eventRecord);+ }+private async processDatasetRunItemEventList(params: {projectId: string;entityId: string;@@ -1334,9 +1532,104 @@ export class IngestionService {return typeof obj === "string" ? obj : JSON.stringify(obj);}+ private getNanosecondTimestamp(timestamp?: string | null): number {+ return timestamp ? new Date(timestamp).getTime() * 1000 : Date.now() * 1000;+ }+private getMillisecondTimestamp(timestamp?: string | null): number {return timestamp ? new Date(timestamp).getTime() : Date.now();}++ /**+ * Flattens a nested JSON object into path-based names and values.+ * For example: {foo: {bar: "baz"}} becomes:+ * - names: ["foo.bar"]+ * - values: ["baz"]+ */+ private flattenJsonToPathArrays(+ obj: Record<string, unknown>,+ prefix: string = "",+ ): { names: string[]; values: unknown[] } {+ const names: string[] = [];+ const values: unknown[] = [];++ for (const [key, value] of Object.entries(obj)) {+ const path = prefix ? `${prefix}.${key}` : key;++ if (+ value !== null &&+ value !== undefined &&+ typeof value === "object" &&+ !Array.isArray(value)+ ) {+ // Recursively flatten nested objects+ const nested = this.flattenJsonToPathArrays(+ value as Record<string, unknown>,+ path,+ );+ names.push(...nested.names);+ values.push(...nested.values);+ } else {+ // Leaf value+ names.push(path);+ values.push(value);+ }+ }++ return { names, values };+ }++ /**+ * Flattens a nested JSON object into type-specific path arrays.+ * Values are separated into string, number, bool, and other arrays based on their type.+ * Non-primitive values are JSON.stringify'd and placed in the strings group.+ */+ private flattenJsonToTypedPathArrays(obj: Record<string, unknown>): {+ stringNames: string[];+ stringValues: string[];+ numberNames: string[];+ numberValues: number[];+ boolNames: string[];+ boolValues: number[]; // ClickHouse uses 0/1 for booleans+ } {+ const stringNames: string[] = [];+ const stringValues: string[] = [];+ const numberNames: string[] = [];+ const numberValues: number[] = [];+ const boolNames: string[] = [];+ const boolValues: number[] = [];++ const { names, values } = this.flattenJsonToPathArrays(obj);++ for (let i = 0; i < names.length; i++) {+ const name = names[i];+ const value = values[i];++ if (typeof value === "boolean") {+ boolNames.push(name);+ boolValues.push(value ? 1 : 0);+ } else if (typeof value === "number") {+ numberNames.push(name);+ numberValues.push(value);+ } else if (typeof value === "string") {+ stringNames.push(name);+ stringValues.push(value);+ } else {+ // For arrays, objects, null, undefined, etc., stringify and put in strings+ stringNames.push(name);+ stringValues.push(JSON.stringify(value));+ }+ }++ return {+ stringNames,+ stringValues,+ numberNames,+ numberValues,+ boolNames,+ boolValues,+ };+ }}type ObservationPrompt = Pick<Prompt, "id" | "name" | "version">;