🪢 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: add remaining columns to new event table schema (#10215)
Steffen Schmitzb60231655ccd
diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex 1ef1d84bf9..30e72c25d9 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -139,10 +139,12 @@ CREATE TABLE IF NOT EXISTS eventstype LowCardinality(String),environment LowCardinality(String) DEFAULT 'default',version String,+ release String,user_id String,session_id String,+ tags Array(String),bookmarked Bool DEFAULT false,public Bool DEFAULT false,@@ -177,38 +179,27 @@ CREATE TABLE IF NOT EXISTS eventsoutput Decimal(18,12),total Decimal(18,12),),- total_cost Decimal(18,12), -- 0 if not provided+ total_cost Decimal(18, 12) ALIAS cost_details.total,-- I/Oinput String CODEC(ZSTD(3)),input_truncated String MATERIALIZED leftUTF8(input, 1024),+ input_length UInt64 MATERIALIZED lengthUTF8(input),output String CODEC(ZSTD(3)),output_truncated String MATERIALIZED leftUTF8(output, 1024),+ output_length UInt64 MATERIALIZED lengthUTF8(output),- -- TODO Metadata: Decide for approach- -- -- Approach 1: Use plain JSON type with default config+ -- Metadata+ -- Keep raw JSON to benefit from future ClickHouse improvements.+ -- For now, store things as "German Strings" with fast prefix matches based on https://www.uber.com/en-DE/blog/logging/.metadata JSON,- -- -- Approach 2: Uses ideas from https://www.uber.com/en-DE/blog/logging/- -- -- but uses Dynamic type to make this a single listmetadata_names Array(String),- metadata_values Array(Dynamic(max_types=32)),- -- -- Approach 3: 1:1 copy of https://www.uber.com/en-DE/blog/logging/- -- -- May require further high-level types and lots of thought during- -- -- write and query-time.- -- -- metadata_string_names Array(String),- -- -- metadata_string_values Array(String),- -- -- metadata_number_names Array(String),- -- -- metadata_number_values Array(Float64),- -- -- metadata_bool_names Array(String),- -- -- metadata_bool_values Array(UInt8),- -- -- Approach 4: Apply German strings here, where we store a prefix and for longer values a pointer.- -- TODO CHANGE MATERIALIZATION (e.g. rename metadata_prefixes to metadata_values)- metadata_keys Array(String) MATERIALIZED metadata_names,- metadata_prefixes Array(String) MATERIALIZED arrayMap(v -> leftUTF8(CAST(v, 'String'), 200), metadata_values),- metadata_hashes Array(Nullable(UInt32)) MATERIALIZED arrayMap(v -> if(lengthUTF8(CAST(v, 'String')) > 200, xxHash32(CAST(v, 'String')), NULL), metadata_values),+ metadata_raw_values Array(String), -- should not be used on retrieval, only for materializing other columns+ metadata_prefixes Array(String) MATERIALIZED arrayMap(v -> leftUTF8(CAST(v, 'String'), 200), metadata_raw_values),+ metadata_hashes Array(Nullable(UInt32)) MATERIALIZED arrayMap(v -> if(lengthUTF8(CAST(v, 'String')) > 200, xxHash32(CAST(v, 'String')), NULL), metadata_raw_values),metadata_long_values Map(UInt32, String) MATERIALIZED mapFromArrays(- arrayMap(v -> xxHash32(CAST(v, 'String')), arrayFilter(v -> lengthUTF8(CAST(v, 'String')) > 200, metadata_values)),- arrayMap(v -> CAST(v, 'String'), arrayFilter(v -> lengthUTF8(CAST(v, 'String')) > 200, metadata_values))+ arrayMap(v -> xxHash32(CAST(v, 'String')), arrayFilter(v -> lengthUTF8(CAST(v, 'String')) > 200, metadata_raw_values)),+ arrayMap(v -> CAST(v, 'String'), arrayFilter(v -> lengthUTF8(CAST(v, 'String')) > 200, metadata_raw_values))),-- Experiment properties@@ -236,7 +227,6 @@ CREATE TABLE IF NOT EXISTS events-- Generic propsblob_storage_file_path String,- -- event_raw String,event_bytes UInt64,created_at DateTime64(6) DEFAULT now(),updated_at DateTime64(6) DEFAULT now(),@@ -290,10 +280,10 @@ clickhouse client \--multiquery <<EOFTRUNCATE events;INSERT INTO events (project_id, trace_id, span_id, parent_span_id, start_time, end_time, name, type,- environment, version, user_id, session_id, public, bookmarked, level, status_message, completion_start_time, prompt_id,+ environment, version, release, tags, user_id, session_id, public, bookmarked, level, status_message, completion_start_time, prompt_id,prompt_name, prompt_version, model_id, provided_model_name, model_parameters,- provided_usage_details, usage_details, provided_cost_details, cost_details, total_cost, input,- output, metadata, metadata_names, metadata_values,+ provided_usage_details, usage_details, provided_cost_details, cost_details, input,+ output, metadata, metadata_names, metadata_raw_values,-- metadata_string_names, metadata_string_values, metadata_number_names, metadata_number_values, metadata_bool_names, metadata_bool_values,source, service_name, service_version, scope_name, scope_version, telemetry_sdk_language,telemetry_sdk_name, telemetry_sdk_version, blob_storage_file_path, event_bytes,@@ -308,6 +298,8 @@ clickhouse client \o.type,o.environment,o.version,+ t.release as release,+ t.tags as tags,t.user_id AS user_id,t.session_id AS session_id,t.public AS public,@@ -325,12 +317,11 @@ clickhouse client \o.usage_details,o.provided_cost_details,o.cost_details,- ifNull(o.total_cost, 0) AS total_cost,ifNull(o.input, '') AS input,ifNull(o.output, '') AS output,CAST(o.metadata, 'JSON'),- mapKeys(o.metadata) AS \`metadata.names\`,- mapValues(o.metadata) AS \`metadata.values\`,+ mapKeys(o.metadata) AS metadata_names,+ mapValues(o.metadata) AS metadata_raw_values,multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,NULL AS service_name,NULL AS service_version,diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex 4830035102..e611a7239c 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -190,6 +190,8 @@ export class OtelIngestionProcessor {const events: any[] = [];for (const scopeSpan of resourceSpan?.scopeSpans ?? []) {+ const isLangfuseSDKSpans =+ scopeSpan.scope?.name?.startsWith("langfuse-sdk") ?? false;const scopeAttributes = this.extractScopeAttributes(scopeSpan);for (const span of scopeSpan?.spans ?? []) {const spanAttributes = this.extractSpanAttributes(span);@@ -333,8 +335,19 @@ export class OtelIngestionProcessor {startTimeISO,),- // TODO: Usage details+ // Usage and cost details+ providedUsageDetails: this.extractUsageDetails(+ spanAttributes,+ scopeSpan?.scope?.name ?? "",+ ),+ providedCostDetails: this.extractCostDetails(+ spanAttributes,+ isLangfuseSDKSpans,+ ),+ // Properties+ tags: this.extractTags(spanAttributes),+ public: this.extractPublic(spanAttributes),userId: this.extractUserId(spanAttributes),sessionId: this.extractSessionId(spanAttributes),@@ -743,7 +756,7 @@ export class OtelIngestionProcessor {null,userId: this.extractUserId(attributes),sessionId: this.extractSessionId(attributes),- public: this.isTracePublic(attributes),+ public: this.extractPublic(attributes),tags: this.extractTags(attributes),environment: this.extractEnvironment(attributes, resourceAttributes),input,@@ -778,7 +791,7 @@ export class OtelIngestionProcessor {null,userId: this.extractUserId(attributes),sessionId: this.extractSessionId(attributes),- public: this.isTracePublic(attributes),+ public: this.extractPublic(attributes),tags: this.extractTags(attributes),environment: this.extractEnvironment(attributes, resourceAttributes),input: attributes[LangfuseOtelSpanAttributes.TRACE_INPUT],@@ -802,7 +815,7 @@ export class OtelIngestionProcessor {};}- private isTracePublic(+ private extractPublic(attributes?: Record<string, unknown>,): boolean | undefined {const value =@@ -810,8 +823,7 @@ export class OtelIngestionProcessor {attributes?.["langfuse.public"];if (value == null) return;-- return value === true || value === "true" ? true : false;+ return value === true || value === "true";}private createObservationEvent(diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.tsindex 6c84e744af..43ea9ef0ac 100644--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts@@ -224,7 +224,7 @@ export class CategoryOptionsFilter implements Filter {// stringObject filter is used when we want to filter on a key value pair in metadata.// For observations/traces tables: uses Map column (metadata)-// For events table: uses Array columns (metadata_names/metadata_values)+// For events table: uses Array columns (metadata_names/metadata_prefixes)// We can only filter efficiently on the first level of a json obj.export class StringObjectFilter implements Filter {public clickhouseTable: string;@@ -255,15 +255,15 @@ export class StringObjectFilter implements Filter {const varValueName = `stringObjectValueFilter${clickhouseCompliantRandomCharacters()}`;const prefix = this.tablePrefix ? this.tablePrefix + "." : "";- // Events table uses array columns (metadata_names/metadata_values)+ // Events table uses array columns (metadata_names/metadata_prefixes)// Observations/traces tables use Map column (metadata)const isEventsTable = this.clickhouseTable === "events";let query: string;if (isEventsTable) {- // For events table, use array access: metadata_values[indexOf(metadata_names, key)]+ // For events table, use array access: metadata_prefixes[indexOf(metadata_names, key)]const namesColumn = `${prefix}metadata_names`;- const valuesColumn = `${prefix}metadata_values`;+ const valuesColumn = `${prefix}metadata_prefixes`;const valueAccessor = `${valuesColumn}[indexOf(${namesColumn}, {${varKeyName}: String})]`;switch (this.operator) {diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex c8f93c7293..b657ebb2fd 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -50,7 +50,7 @@ const EVENTS_FIELDS = {// I/O & metadata fieldsinput: "e.input",output: "e.output",- metadata: "mapFromArrays(e.metadata_names, e.metadata_values) as metadata",+ metadata: "mapFromArrays(e.metadata_names, e.metadata_prefixes) as metadata",// Calculated fieldslatency:@@ -156,7 +156,7 @@ const EVENTS_AGGREGATION_FIELDS = {output_truncated:"argMaxIf(output_truncated, event_ts, parent_span_id = '') AS output_truncated",metadata:- "argMaxIf(mapFromArrays(e.metadata_names, e.metadata_values), event_ts, parent_span_id = '') AS metadata",+ "argMaxIf(mapFromArrays(e.metadata_names, e.metadata_prefixes), event_ts, parent_span_id = '') AS metadata",created_at: "min(created_at) AS created_at",updated_at: "max(updated_at) AS updated_at",total_cost: "sum(total_cost) AS total_cost",diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex a0f3adcb2f..2fb49541f4 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -357,6 +357,8 @@ export async function queryClickhouse<T>(opts: {format: "JSONEachRow",query_params: opts.params,clickhouse_settings: {+ asterisk_include_alias_columns: 1,+ asterisk_include_materialized_columns: 1,...opts.clickhouseSettings,log_comment: JSON.stringify(opts.tags ?? {}),},diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex 5d5c8d7e73..a22ae00781 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -605,11 +605,13 @@ export const eventRecordBaseSchema = z.object({type: z.string(),environment: z.string().default("default"),version: z.string().nullish(),+ release: z.string().nullish(),user_id: z.string().nullish(),session_id: z.string().nullish(),// User updatable flags+ tags: z.array(z.string()).default([]),bookmarked: z.boolean().optional(),public: z.boolean().optional(),@@ -631,22 +633,27 @@ export const eventRecordBaseSchema = z.object({usage_details: UsageCostSchema,provided_cost_details: UsageCostSchema,cost_details: UsageCostSchema,- total_cost: z.number().nullish(),// I/Oinput: z.string().nullish(),output: z.string().nullish(),- // Metadata - multiple approaches supported+ // Metadatametadata: 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([]),++ // Experiment properties+ experiment_id: z.string().nullish(),+ experiment_name: z.string().nullish(),+ experiment_metadata_names: z.array(z.string()).default([]),+ experiment_metadata_values: z.array(z.string().nullish()).default([]),+ experiment_description: z.string().nullish(),+ experiment_dataset_id: z.string().nullish(),+ experiment_item_id: z.string().nullish(),+ experiment_item_expected_output: z.string().nullish(),+ experiment_item_metadata_names: z.array(z.string()).default([]),+ experiment_item_metadata_values: z.array(z.string().nullish()).default([]),+ experiment_item_root_span_id: z.string().nullish(),// Source metadata (Instrumentation)source: z.string(),@@ -665,6 +672,11 @@ export const eventRecordBaseSchema = z.object({});export const eventRecordReadSchema = eventRecordBaseSchema.extend({+ metadata_prefixes: z.array(z.string()).default([]),+ metadata_hashes: z.array(z.number().int()).default([]),+ metadata_long_values: z.record(z.number().int(), z.string()).default({}),+ total_cost: z.number().nullish(),+start_time: clickhouseStringDateSchema,end_time: clickhouseStringDateSchema.nullish(),completion_start_time: clickhouseStringDateSchema.nullish(),@@ -675,6 +687,7 @@ export const eventRecordReadSchema = eventRecordBaseSchema.extend({export type EventRecordReadType = z.infer<typeof eventRecordReadSchema>;export const eventRecordInsertSchema = eventRecordBaseSchema.extend({+ metadata_raw_values: z.array(z.string().nullish()).default([]),start_time: z.number(),end_time: z.number().nullish(),completion_start_time: z.number().nullish(),diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex 0bbc235b47..b8c88a882d 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -205,7 +205,6 @@ export const createEvent = (return {// Identifiers- org_id: null,project_id: v4(),trace_id: v4(),span_id: spanId,@@ -217,6 +216,9 @@ export const createEvent = (type: "GENERATION",environment: "default",version: null,+ release: null,++ tags: [],user_id: null,session_id: null,@@ -239,7 +241,6 @@ export const createEvent = (usage_details: { input: 1234, output: 5678, total: 6912 },provided_cost_details: { input: 100, output: 200, total: 300 },cost_details: { input: 100, output: 200, total: 300 },- total_cost: 300,// I/Oinput: "Hello World",@@ -248,13 +249,20 @@ export const createEvent = (// Metadata - populate both JSON and array columnsmetadata: finalMetadata,metadata_names: metadataNames,- metadata_values: metadataValues,- // metadata_string_names: [],- // metadata_string_values: [],- // metadata_number_names: [],- // metadata_number_values: [],- // metadata_bool_names: [],- // metadata_bool_values: [],+ metadata_raw_values: metadataValues,++ // Experiment properties+ experiment_id: null,+ experiment_name: null,+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_description: null,+ experiment_dataset_id: null,+ experiment_item_id: null,+ experiment_item_expected_output: null,+ experiment_item_metadata_names: [],+ experiment_item_metadata_values: [],+ experiment_item_root_span_id: null,// Source metadata (Instrumentation)source: "API",diff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/async/observations-api.servertest.tsindex 4865b55f9c..48a9ecb221 100644--- a/web/src/__tests__/async/observations-api.servertest.ts+++ b/web/src/__tests__/async/observations-api.servertest.ts@@ -56,7 +56,9 @@ const createObservationData = (output: data.output !== undefined ? data.output : "Hello John",metadata: data.metadata ?? { source: "API", server: "Node" },metadata_names: data.metadata ? Object.keys(data.metadata) : undefined,- metadata_values: data.metadata ? Object.values(data.metadata) : undefined,+ metadata_raw_values: data.metadata+ ? Object.values(data.metadata)+ : undefined,provided_model_name: data.provided_model_name,provided_usage_details: data.provided_usage_details,provided_cost_details: data.provided_cost_details,diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex eb9e280bd5..45b083d014 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -47,6 +47,8 @@ type ObservationEventData = {provided_model_name?: string;provided_usage_details?: Record<string, number>;provided_cost_details?: Record<string, number>;+ usage_details?: Record<string, number>;+ cost_details?: Record<string, number>;total_cost?: number;};@@ -126,7 +128,9 @@ const createTraceWithObservations = async (input: trace.input ?? null,output: trace.output ?? null,metadata: trace.metadata ?? {},- total_cost: 0, // Root trace event has no cost+ cost_details: {+ total: 0, // Root trace event has no cost+ },});const observationEvents = observations.map((obs) =>@@ -1629,6 +1633,9 @@ describe("/api/public/traces API Endpoint", () => {end_time: timestamp.getTime() + 1000,input: "What is the capital of France?",output: "The capital of France is Paris.",+ cost_details: {+ total: 0.05,+ },total_cost: 0.05,metadata: { testKey: "testValue" },},@@ -1639,6 +1646,9 @@ describe("/api/public/traces API Endpoint", () => {type: "SPAN",start_time: timestamp.getTime() + 500,end_time: timestamp.getTime() + 2000,+ cost_details: {+ total: 0.03,+ },total_cost: 0.03,metadata: { testKey: "testValue" },},diff --git a/worker/src/backgroundMigrations/backfillEventsHistoric.ts b/worker/src/backgroundMigrations/backfillEventsHistoric.tsindex 875f855049..90182ebb84 100644--- a/worker/src/backgroundMigrations/backfillEventsHistoric.ts+++ b/worker/src/backgroundMigrations/backfillEventsHistoric.ts@@ -9,6 +9,8 @@ import { prisma } from "@langfuse/shared/src/db";import { env } from "../env";import { parseArgs } from "node:util";+// TODO: This is WIP and should not be used for actual backfills.+// This is hard-coded in our migrations and uniquely identifies the row in background_migrations tableconst backgroundMigrationId = "d8cf9f5e-747e-4ffe-8156-dec0eaebce9d";@@ -272,12 +274,11 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {usage_details,provided_cost_details,cost_details,- total_cost,input,output,- -- metadata,+ metadata,metadata_names,- metadata_values,+ metadata_raw_values,source,service_name,service_version,@@ -324,12 +325,11 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {o.usage_details,o.provided_cost_details,o.cost_details,- coalesce(o.total_cost, 0) AS total_cost,coalesce(o.input, '') AS input,coalesce(o.output, '') AS output,- -- CAST(mapConcat(o.metadata, coalesce(t.metadata, map())), 'JSON') AS metadata,+ CAST(mapConcat(o.metadata, coalesce(t.metadata, map())), 'JSON') AS metadata,mapKeys(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_names,- mapValues(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_values,+ mapValues(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_raw_values,multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,NULL AS service_name,NULL AS service_version,diff --git a/worker/src/features/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.tsindex 981d17e263..3c6fa0843d 100644--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts@@ -230,6 +230,11 @@ export const handleEventPropagationJob = async (t.project_id,t.user_id,t.session_id,+ t.version,+ t.release,+ t.tags,+ t.bookmarked,+ t.public,t.metadatafrom traces twhere t.project_id in (select arrayJoin(project_ids) from batch_stats)@@ -251,6 +256,10 @@ export const handleEventPropagationJob = async (type,environment,version,+ release,+ tags,+ public,+ bookmarked,user_id,session_id,level,@@ -266,26 +275,12 @@ export const handleEventPropagationJob = async (usage_details,provided_cost_details,cost_details,- total_cost,input,output,metadata,metadata_names,- metadata_values,- -- metadata_string_names,- -- metadata_string_values,- -- metadata_number_names,- -- metadata_number_values,- -- metadata_bool_names,- -- metadata_bool_values,+ metadata_raw_values,source,- service_name,- service_version,- scope_name,- scope_version,- telemetry_sdk_language,- telemetry_sdk_name,- telemetry_sdk_version,blob_storage_file_path,event_bytes,created_at,@@ -310,7 +305,11 @@ export const handleEventPropagationJob = async (obs.name,obs.type,obs.environment,- obs.version,+ coalesce(obs.version, t.version) as version,+ coalesce(t.release, '') as release,+ t.tags as tags,+ t.public as public,+ t.bookmarked AND (obs.parent_observation_id IS NULL OR obs.parent_observation_id = '') AS bookmarked,coalesce(t.user_id, '') AS user_id,coalesce(t.session_id, '') AS session_id,obs.level,@@ -326,27 +325,13 @@ export const handleEventPropagationJob = async (obs.usage_details,obs.provided_cost_details,obs.cost_details,- coalesce(obs.total_cost, 0) AS total_cost,coalesce(obs.input, '') AS input,coalesce(obs.output, '') AS output,-- Merge trace and observation metadata, with observation taking precedence (first map wins)CAST(mapConcat(obs.metadata, coalesce(t.metadata, map())), 'JSON') AS metadata,mapKeys(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_names,- mapValues(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_values,- -- mapKeys(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_string_names,- -- mapValues(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_string_values,- -- [] AS metadata_number_names,- -- [] AS metadata_number_values,- -- [] AS metadata_bool_names,- -- [] AS metadata_bool_values,+ mapValues(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_raw_values,multiIf(mapContains(obs.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,- NULL AS service_name,- NULL AS service_version,- NULL AS scope_name,- NULL AS scope_version,- NULL AS telemetry_sdk_language,- NULL AS telemetry_sdk_name,- NULL AS telemetry_sdk_version,'' AS blob_storage_file_path,byteSize(*) AS event_bytes,obs.created_at,diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.tsindex beff362529..719a8ea45e 100644--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts@@ -13,6 +13,8 @@ import { prisma } from "@langfuse/shared/src/db";const EXPERIMENT_BACKFILL_TIMESTAMP_KEY ="langfuse:event-propagation:experiment-backfill:last-run";+const EXPERIMENT_BACKFILL_LOCK_KEY = "langfuse:experiment-backfill:lock";+const LOCK_TTL_SECONDS = 300; // 5 minutesinterface DatasetRunItem {id: string;@@ -41,6 +43,7 @@ interface SpanRecord {type: string;environment: string;version: string;+ release: string;input: string;output: string;// Add other fields as needed from observations/traces@@ -59,6 +62,10 @@ interface SpanRecord {cost_details: Record<string, number> | null;total_cost: number;metadata: Record<string, unknown>;+ source: string;+ tags: Array<string>;+ bookmarked: boolean;+ public: boolean;user_id: string;session_id: string;}@@ -77,6 +84,16 @@ interface EnrichedSpan extends SpanRecord {experiment_item_metadata_values: Array<string | null | undefined>;}+interface TraceProperties {+ userId: string;+ sessionId: string;+ version: string;+ release: string;+ tags: string[];+ bookmarked: boolean;+ public: boolean;+}+/*** Fetch dataset run items created within a time window.* Deduplicates by (project_id, trace_id, observation_id) taking the most recent.@@ -167,6 +184,7 @@ export async function getRelevantObservations(o.type,coalesce(o.environment, '') AS environment,coalesce(o.version, '') AS version,+ '' as release,coalesce(o.input, '') AS input,coalesce(o.output, '') AS output,o.level AS level,@@ -184,6 +202,10 @@ export async function getRelevantObservations(o.cost_details AS cost_details,coalesce(o.total_cost, 0) AS total_cost,o.metadata,+ multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,+ [] as tags,+ false AS bookmarked,+ false AS public,'' AS user_id,'' AS session_idFROM observations o@@ -232,6 +254,7 @@ export async function getRelevantTraces('SPAN' AS type,coalesce(t.environment, '') AS environment,coalesce(t.version, '') AS version,+ coalesce(t.release, '') AS release,coalesce(t.input, '') AS input,coalesce(t.output, '') AS output,'' AS level,@@ -249,6 +272,10 @@ export async function getRelevantTraces(map() AS cost_details,0 AS total_cost,t.metadata,+ multiIf(mapContains(t.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,+ t.tags,+ t.bookmarked,+ t.public,coalesce(t.user_id, '') AS user_id,coalesce(t.session_id, '') AS session_idFROM traces t@@ -326,9 +353,17 @@ export function findAllChildren(*/function convertToEnrichedSpanWithoutExperiment(span: SpanRecord,+ traceProperties: TraceProperties | undefined,): EnrichedSpan {return {...span,+ user_id: traceProperties?.userId || "",+ session_id: traceProperties?.sessionId || "",+ version: span.version || traceProperties?.version || "",+ release: traceProperties?.release || "",+ tags: traceProperties?.tags || [],+ bookmarked: traceProperties?.bookmarked || false,+ public: traceProperties?.public || false,experiment_id: "",experiment_name: "",experiment_metadata_names: [],@@ -351,7 +386,7 @@ export function enrichSpansWithExperiment(rootSpan: SpanRecord,childSpans: SpanRecord[],dri: DatasetRunItem,- traceProperties: { userId: string; sessionId: string },+ traceProperties: TraceProperties | undefined,): EnrichedSpan[] {const enrichedSpans: EnrichedSpan[] = [];@@ -365,8 +400,13 @@ export function enrichSpansWithExperiment(// Enrich root spanenrichedSpans.push({...rootSpan,- user_id: traceProperties.userId,- session_id: traceProperties.sessionId,+ user_id: traceProperties?.userId || "",+ session_id: traceProperties?.sessionId || "",+ version: rootSpan.version || traceProperties?.version || "",+ release: traceProperties?.release || "",+ tags: traceProperties?.tags || [],+ bookmarked: traceProperties?.bookmarked || false,+ public: traceProperties?.public || false,experiment_id: dri.dataset_run_id,experiment_name: dri.dataset_run_name,experiment_metadata_names: experimentMetadataFlattened.names,@@ -384,8 +424,12 @@ export function enrichSpansWithExperiment(for (const child of childSpans) {enrichedSpans.push({...child,- user_id: traceProperties.userId,- session_id: traceProperties.sessionId,+ user_id: traceProperties?.userId || "",+ session_id: traceProperties?.sessionId || "",+ version: child.version || traceProperties?.version || "",+ release: traceProperties?.release || "",+ tags: traceProperties?.tags || [],+ public: traceProperties?.public || false,experiment_id: dri.dataset_run_id,experiment_name: dri.dataset_run_name,experiment_metadata_names: experimentMetadataFlattened.names,@@ -441,6 +485,10 @@ async function writeEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {type: span.type,environment: span.environment || undefined,version: span.version || undefined,+ release: span.release || undefined,+ tags: span.tags || [],+ bookmarked: span.bookmarked || false,+ public: span.public || false,completionStartTime: span.completion_start_time || undefined,// User/session@@ -473,7 +521,7 @@ async function writeEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {metadata: span.metadata,// Source/instrumentation- source: "ingestion-api",+ source: span.source,// Experiment fieldsexperimentId: span.experiment_id,@@ -554,15 +602,65 @@ export async function initializeBackfillCutoff(): Promise<Date> {}/**- * Check if the experiment backfill should run based on the throttle.+ * Check if the experiment backfill should run based on the throttle and lock acquisition.* (Default every 5min).*- * @returns true if backfill should run (>5min since last run), false otherwise+ * First checks if enough time has passed since the last run.+ * Then attempts to acquire a distributed lock to ensure only one worker runs the backfill.+ *+ * @returns true if backfill should run (time threshold passed AND lock acquired), false otherwise*/export async function shouldRunBackfill(lastRun: Date): Promise<boolean> {+ // First check time-based throttleconst now = new Date();const timeSinceLastRun = now.getTime() - lastRun.getTime();- return timeSinceLastRun >= env.LANGFUSE_EXPERIMENT_BACKFILL_THROTTLE_MS;++ if (timeSinceLastRun < env.LANGFUSE_EXPERIMENT_BACKFILL_THROTTLE_MS) {+ logger.debug(+ "[EXPERIMENT BACKFILL] Skipping due to throttle (time threshold not met)",+ );+ return false;+ }++ // Time threshold passed, now try to acquire lock+ if (!redis) {+ logger.warn(+ "[EXPERIMENT BACKFILL] Redis not available, skipping lock acquisition",+ );+ return true; // Allow processing if Redis is unavailable+ }++ try {+ // Try to acquire lock using Redis SET NX (atomic test-and-set)+ const result = await redis.set(+ EXPERIMENT_BACKFILL_LOCK_KEY,+ "true",+ "EX",+ LOCK_TTL_SECONDS,+ "NX",+ );++ const acquired = result === "OK";++ if (acquired) {+ logger.info(+ `[EXPERIMENT BACKFILL] Acquired backfill lock with TTL ${LOCK_TTL_SECONDS}s`,+ );+ } else {+ logger.debug(+ "[EXPERIMENT BACKFILL] Backfill is already locked by another worker",+ );+ }++ return acquired;+ } catch (error) {+ logger.error(+ "[EXPERIMENT BACKFILL] Failed to acquire backfill lock",+ error,+ );+ // On error, allow processing to avoid blocking the system+ return true;+ }}/**@@ -690,14 +788,16 @@ async function processExperimentBackfill(const { spanMap, childMap } = buildSpanMaps(allSpans);// Build a map of trace_id -> {userId, sessionId} for efficient lookup- const tracePropertiesMap = new Map<- string,- { userId: string; sessionId: string }- >();+ const tracePropertiesMap = new Map<string, TraceProperties>();for (const trace of traces) {tracePropertiesMap.set(trace.trace_id, {userId: trace.user_id,sessionId: trace.session_id,+ version: trace.version,+ release: trace.release,+ tags: trace.tags,+ bookmarked: trace.bookmarked,+ public: trace.public,});}@@ -718,10 +818,7 @@ async function processExperimentBackfill(}// Get trace-level properties for this trace- const traceProperties = tracePropertiesMap.get(dri.trace_id) || {- userId: "",- sessionId: "",- };+ const traceProperties = tracePropertiesMap.get(dri.trace_id);// Find all children recursivelyconst childSpans = findAllChildren(rootSpanId, childMap);@@ -746,7 +843,10 @@ async function processExperimentBackfill(// Add all remaining spans that weren't enriched (e.g., trace-derived spans that weren't roots)for (const span of allSpans) {if (!processedSpanIds.has(span.span_id)) {- allEnrichedSpans.push(convertToEnrichedSpanWithoutExperiment(span));+ const traceProperties = tracePropertiesMap.get(span.trace_id);+ allEnrichedSpans.push(+ convertToEnrichedSpanWithoutExperiment(span, traceProperties),+ );}}diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 27c31b3e26..2f2136ee2a 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -86,9 +86,14 @@ export type EventInput = {type?: string;environment?: string;version?: string;+ release?: string;endTimeISO: string;completionStartTime?: string;+ tags?: string[];+ bookmarked?: boolean;+ public?: boolean;+// User/sessionuserId?: string;sessionId?: string;@@ -101,6 +106,7 @@ export type EventInput = {promptVersion?: string;// Model+ modelId?: string;modelName?: string;modelParameters?: string | Record<string, unknown>;@@ -109,7 +115,6 @@ export type EventInput = {usageDetails?: Record<string, number>;providedCostDetails?: Record<string, number>;costDetails?: Record<string, number>;- totalCost?: number;// I/Oinput?: string;@@ -278,25 +283,48 @@ export class IngestionService {`Writing event for project ${eventData.projectId} and span ${eventData.spanId}`,);+ // Perform lookups for prompt and model/usage enrichment+ const [prompt, generationUsage] = await Promise.all([+ // Lookup prompt by name and version+ eventData.promptName && eventData.promptVersion+ ? this.promptService.getPrompt({+ projectId: eventData.projectId,+ promptName: eventData.promptName,+ version:+ typeof eventData.promptVersion === "string"+ ? parseInt(eventData.promptVersion, 10)+ : eventData.promptVersion,+ label: undefined,+ })+ : null,+ // Lookup model and enrich usage/cost details (includes tokenization if needed)+ eventData.modelName+ ? this.getGenerationUsage({+ projectId: eventData.projectId,+ observationRecord: {+ id: eventData.spanId,+ project_id: eventData.projectId,+ trace_id: eventData.traceId,+ provided_model_name: eventData.modelName,+ provided_usage_details: eventData.providedUsageDetails ?? {},+ provided_cost_details: eventData.providedCostDetails ?? {},+ input: eventData.input,+ output: eventData.output,+ },+ })+ : null,+ ]);+const now = this.getMicrosecondTimestamp();// Store the full metadata JSON- const metadata = eventData.metadata;+ const metadata = convertRecordValuesToString(eventData.metadata);// Flatten to path-based arraysconst flattened = 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 identifiersid: eventData.spanId,@@ -312,6 +340,11 @@ export class IngestionService {type: eventData.type ?? "SPAN",environment: eventData.environment ?? "default",version: eventData.version,+ release: eventData.release,++ tags: eventData.tags ?? [],+ bookmarked: eventData.bookmarked ?? false,+ public: eventData.public ?? false,// User/sessionuser_id: eventData.userId,@@ -329,12 +362,12 @@ export class IngestionService {: null,// Prompt- // prompt_id: eventData.promptId,+ prompt_id: prompt?.id || "",prompt_name: eventData.promptName,prompt_version: eventData.promptVersion,// Model- // model_id: eventData.modelId,+ model_id: generationUsage?.internal_model_id || "",provided_model_name: eventData.modelName,model_parameters: eventData.modelParameters? typeof eventData.modelParameters === "string"@@ -343,26 +376,21 @@ export class IngestionService {: {},// Usage & Cost- // provided_usage_details: eventData.providedUsageDetails ?? {},- // usage_details: eventData.usageDetails ?? {},- // provided_cost_details: eventData.providedCostDetails ?? {},- // cost_details: eventData.costDetails ?? {},- // total_cost: eventData.totalCost,+ provided_usage_details: eventData.providedUsageDetails ?? {},+ usage_details:+ generationUsage?.usage_details ?? eventData.usageDetails ?? {},+ provided_cost_details: eventData.providedCostDetails ?? {},+ cost_details:+ generationUsage?.cost_details ?? eventData.costDetails ?? {},// I/Oinput: eventData.input,output: eventData.output,- // Metadata (multiple approaches)+ // Metadatametadata,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,+ metadata_raw_values: metadataValues,// Source/instrumentation metadatasource: eventData.source,@@ -381,22 +409,24 @@ export class IngestionService {// Experiment fieldsexperiment_id: eventData.experimentId,experiment_name: eventData.experimentName,- experiment_metadata_names: eventData.experimentMetadataNames,- experiment_metadata_values: eventData.experimentMetadataValues,+ experiment_metadata_names: eventData.experimentMetadataNames ?? [],+ experiment_metadata_values: eventData.experimentMetadataValues ?? [],experiment_description: eventData.experimentDescription,experiment_dataset_id: eventData.experimentDatasetId,experiment_item_id: eventData.experimentItemId,experiment_item_root_span_id: eventData.experimentItemRootSpanId,experiment_item_expected_output: eventData.experimentItemExpectedOutput,- experiment_item_metadata_names: eventData.experimentItemMetadataNames,- experiment_item_metadata_values: eventData.experimentItemMetadataValues,+ experiment_item_metadata_names:+ eventData.experimentItemMetadataNames ?? [],+ experiment_item_metadata_values:+ eventData.experimentItemMetadataValues ?? [],// System timestampscreated_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);@@ -1035,13 +1065,23 @@ export class IngestionService {private async getGenerationUsage(params: {projectId: string;- observationRecord: ObservationRecordInsertType;+ observationRecord: Pick<+ ObservationRecordInsertType,+ | "project_id"+ | "trace_id"+ | "id"+ | "provided_model_name"+ | "provided_usage_details"+ | "provided_cost_details"+ | "level"+ | "input"+ | "output"+ >;}): Promise<- | Pick<- ObservationRecordInsertType,- "usage_details" | "cost_details" | "total_cost" | "internal_model_id"- >- | {}+ Pick<+ ObservationRecordInsertType,+ "usage_details" | "cost_details" | "total_cost" | "internal_model_id"+ >> {const { projectId, observationRecord } = params;const { model: internalModel, prices: modelPrices } =@@ -1079,7 +1119,10 @@ export class IngestionService {}private async getUsageUnits(- observationRecord: ObservationRecordInsertType,+ observationRecord: Pick<+ ObservationRecordInsertType,+ "provided_usage_details" | "level" | "input" | "output" | "id"+ >,model: Model | null | undefined,): Promise<Pick<@@ -1207,7 +1250,10 @@ export class IngestionService {static calculateUsageCosts(modelPrices: Price[] | null | undefined,- observationRecord: ObservationRecordInsertType,+ observationRecord: Pick<+ ObservationRecordInsertType,+ "provided_cost_details"+ >,usageUnits: UsageCostType,): Pick<ObservationRecordInsertType, "cost_details" | "total_cost"> {const { provided_cost_details } = observationRecord;