🪢 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: inject dataset_run_item values into events table (#10004)
Steffen Schmitz5825da09a7bb
diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex c7db7aab80..1ef1d84bf9 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -151,14 +151,14 @@ CREATE TABLE IF NOT EXISTS eventscompletion_start_time Nullable(DateTime64(6)),-- Prompt- prompt_id Nullable(String),- prompt_name Nullable(String),- prompt_version Nullable(String),+ prompt_id String,+ prompt_name String,+ prompt_version Nullable(UInt16),-- Model- model_id Nullable(String),- provided_model_name Nullable(String),- model_parameters Nullable(String),+ model_id String,+ provided_model_name String,+ model_parameters JSON,-- Usageprovided_usage_details JSON(max_dynamic_paths=64, max_dynamic_types=8),@@ -187,7 +187,7 @@ CREATE TABLE IF NOT EXISTS events-- TODO Metadata: Decide for approach-- -- Approach 1: Use plain JSON type with default config- metadata JSON(max_dynamic_paths=1024, max_dynamic_types=32),+ 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),@@ -202,6 +202,7 @@ CREATE TABLE IF NOT EXISTS events-- -- 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),@@ -210,6 +211,19 @@ CREATE TABLE IF NOT EXISTS eventsarrayMap(v -> CAST(v, 'String'), arrayFilter(v -> lengthUTF8(CAST(v, 'String')) > 200, metadata_values))),+ -- Experiment properties+ experiment_id String,+ experiment_name String,+ experiment_metadata_names Array(String),+ experiment_metadata_values Array(String), -- We will restrict this to 200 characters on the client.+ experiment_description String,+ experiment_dataset_id String,+ experiment_item_id String,+ experiment_item_expected_output String,+ experiment_item_metadata_names Array(String),+ experiment_item_metadata_values Array(String), -- We will restrict this to 200 characters on the client.+ experiment_item_root_span_id String,+-- Source metadata (Instrumentation)source LowCardinality(String),service_name String,@@ -222,7 +236,7 @@ CREATE TABLE IF NOT EXISTS events-- Generic propsblob_storage_file_path String,- event_raw String,+ -- event_raw String,event_bytes UInt64,created_at DateTime64(6) DEFAULT now(),updated_at DateTime64(6) DEFAULT now(),@@ -256,10 +270,12 @@ CREATE TABLE IF NOT EXISTS eventsSETTINGSindex_granularity = 8192,index_granularity_bytes = '64Mi', -- Default 10MiB. Avoid small granules due to large rows.- min_rows_for_wide_part = 0,- min_bytes_for_wide_part = 0,enable_block_number_column = 1,- enable_block_offset_column = 1;+ enable_block_offset_column = 1+ -- Try without, but re-enable if recent row performance is bad+ -- min_rows_for_wide_part = 0,+ -- min_bytes_for_wide_part = 0+ ;EOF@@ -280,7 +296,7 @@ clickhouse client \output, metadata, metadata_names, metadata_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_raw, event_bytes,+ telemetry_sdk_name, telemetry_sdk_version, blob_storage_file_path, event_bytes,created_at, updated_at, event_ts, is_deleted)SELECT o.project_id,o.trace_id,@@ -324,7 +340,6 @@ clickhouse client \NULL AS telemetry_sdk_name,NULL AS telemetry_sdk_version,'' AS blob_storage_file_path,- '' AS event_raw,0 AS event_bytes,o.created_at,o.updated_at,diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex f844cba39a..9dc3ea8f8a 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -25,6 +25,8 @@ export * from "./llm/testModelCall";export * from "./utils/DatabaseReadStream";export * from "./utils/transforms";export * from "./utils/billingCycleHelpers";+export * from "./utils/compareVersions";+export * from "./otel/utils";export * from "./clickhouse/client";export * from "./clickhouse/schemaUtils";export * from "./clickhouse/schema";diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.tsindex 07db5b3137..4c23a479d5 100644--- a/packages/shared/src/server/ingestion/processEventBatch.ts+++ b/packages/shared/src/server/ingestion/processEventBatch.ts@@ -82,11 +82,13 @@ const getDelay = (delay: number | null, source: "api" | "otel") => {* @property delay - Delay in ms to wait before processing events in the batch.* @property source - Source of the events for metrics tracking (e.g., "otel", "api").* @property isLangfuseInternal - Whether the events are being ingested by Langfuse internally (e.g. traces created for prompt experiments).+ * @property forwardToEventsTable - Whether to forward events to the staging events table for batch propagation. If undefined, falls back to environment flags.*/type ProcessEventBatchOptions = {delay?: number | null;source?: "api" | "otel";isLangfuseInternal?: boolean;+ forwardToEventsTable?: boolean;};/**@@ -111,7 +113,12 @@ export const processEventBatch = async (if (input.length === 0) {return { successes: [], errors: [] };}- const { delay = null, source = "api", isLangfuseInternal = false } = options;+ const {+ delay = null,+ source = "api",+ isLangfuseInternal = false,+ forwardToEventsTable,+ } = options;// add context of api call to the spanconst currentSpan = getCurrentSpan();@@ -306,6 +313,7 @@ export const processEventBatch = async (eventBodyId: eventData.eventBodyId,fileKey: eventData.key,skipS3List: shouldSkipS3List,+ forwardToEventsTable,},authCheck: authCheck as {validKey: true;diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex 89d4d087be..4830035102 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -23,7 +23,7 @@ import { LangfuseOtelSpanAttributes } from "./attributes";import { ObservationTypeMapperRegistry } from "./ObservationTypeMapper";import { env } from "../../env";import { OtelIngestionQueue } from "../redis/otelIngestionQueue";-import { isValidDateString } from "./utils";+import { isValidDateString, flattenJsonToPathArrays } from "./utils";// Type definitions for internal processor stateinterface TraceState {@@ -66,7 +66,7 @@ interface CreateObservationEventParams {endTimeISO: string;}-interface ResourceSpan {+export interface ResourceSpan {resource?: {attributes?: Array<{ key: string; value: any }>;};@@ -266,6 +266,9 @@ export class OtelIngestionProcessor {},);+ const experimentFields =+ this.extractExperimentFields(spanAttributes);+events.push({projectId: this.projectId,traceId,@@ -354,6 +357,9 @@ export class OtelIngestionProcessor {// Source data// eventRaw: stringifiedSpan,eventBytes,++ // Experiment fields+ ...experimentFields,});}}@@ -1987,6 +1993,106 @@ export class OtelIngestionProcessor {return [];}+ /**+ * Extracts experiment-related fields from span attributes.+ * Returns undefined for fields that are not present.+ */+ private extractExperimentFields(attributes: Record<string, unknown>): {+ experimentId?: string;+ experimentName?: string;+ experimentDescription?: string;+ experimentDatasetId?: string;+ experimentItemId?: string;+ experimentItemRootSpanId?: string;+ experimentItemExpectedOutput?: string;+ experimentMetadataNames?: string[];+ experimentMetadataValues?: Array<string | null | undefined>;+ experimentItemMetadataNames?: string[];+ experimentItemMetadataValues?: Array<string | null | undefined>;+ } {+ const experimentId = attributes[LangfuseOtelSpanAttributes.EXPERIMENT_ID];+ const experimentName =+ attributes[LangfuseOtelSpanAttributes.EXPERIMENT_NAME];+ const experimentDescription =+ attributes[LangfuseOtelSpanAttributes.EXPERIMENT_DESCRIPTION];+ const experimentDatasetId =+ attributes[LangfuseOtelSpanAttributes.EXPERIMENT_DATASET_ID];+ const experimentItemId =+ attributes[LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_ID];+ const experimentItemRootSpanId =+ attributes[+ LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_ROOT_OBSERVATION_ID+ ];+ const experimentItemExpectedOutput =+ attributes[LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_EXPECTED_OUTPUT];++ // Extract experiment metadata+ const experimentMetadataStr =+ attributes[LangfuseOtelSpanAttributes.EXPERIMENT_METADATA];+ let experimentMetadata: Record<string, unknown> = {};+ if (experimentMetadataStr && typeof experimentMetadataStr === "string") {+ try {+ experimentMetadata = JSON.parse(experimentMetadataStr);+ } catch (e) {+ // If parsing fails, treat as empty+ }+ }+ const experimentMetadataFlattened =+ flattenJsonToPathArrays(experimentMetadata);++ // Extract experiment item metadata+ const experimentItemMetadataStr =+ attributes[LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_METADATA];+ let experimentItemMetadata: Record<string, unknown> = {};+ if (+ experimentItemMetadataStr &&+ typeof experimentItemMetadataStr === "string"+ ) {+ try {+ experimentItemMetadata = JSON.parse(experimentItemMetadataStr);+ } catch (e) {+ // If parsing fails, treat as empty+ }+ }+ const experimentItemMetadataFlattened = flattenJsonToPathArrays(+ experimentItemMetadata,+ );++ return {+ experimentId: experimentId ? String(experimentId) : undefined,+ experimentName: experimentName ? String(experimentName) : undefined,+ experimentDescription: experimentDescription+ ? String(experimentDescription)+ : undefined,+ experimentDatasetId: experimentDatasetId+ ? String(experimentDatasetId)+ : undefined,+ experimentItemId: experimentItemId ? String(experimentItemId) : undefined,+ experimentItemRootSpanId: experimentItemRootSpanId+ ? String(experimentItemRootSpanId)+ : undefined,+ experimentItemExpectedOutput: experimentItemExpectedOutput+ ? String(experimentItemExpectedOutput)+ : undefined,+ experimentMetadataNames:+ experimentMetadataFlattened.names.length > 0+ ? experimentMetadataFlattened.names+ : undefined,+ experimentMetadataValues:+ experimentMetadataFlattened.values.length > 0+ ? experimentMetadataFlattened.values+ : undefined,+ experimentItemMetadataNames:+ experimentItemMetadataFlattened.names.length > 0+ ? experimentItemMetadataFlattened.names+ : undefined,+ experimentItemMetadataValues:+ experimentItemMetadataFlattened.values.length > 0+ ? experimentItemMetadataFlattened.values+ : undefined,+ };+ }+private parseLangfusePromptFromAISDK(attributes: Record<string, unknown>,): { name: string; version: number } | undefined {diff --git a/packages/shared/src/server/otel/attributes.ts b/packages/shared/src/server/otel/attributes.tsindex 98151e9154..e0c2ebdc8d 100644--- a/packages/shared/src/server/otel/attributes.ts+++ b/packages/shared/src/server/otel/attributes.ts@@ -39,4 +39,15 @@ export enum LangfuseOtelSpanAttributes {// but have a new assignmentTRACE_COMPAT_USER_ID = "langfuse.user.id",TRACE_COMPAT_SESSION_ID = "langfuse.session.id",++ // Experiment attributes+ EXPERIMENT_ID = "langfuse.experiment.id",+ EXPERIMENT_NAME = "langfuse.experiment.name",+ EXPERIMENT_METADATA = "langfuse.experiment.metadata",+ EXPERIMENT_DESCRIPTION = "langfuse.experiment.description",+ EXPERIMENT_DATASET_ID = "langfuse.experiment.dataset.id",+ EXPERIMENT_ITEM_ID = "langfuse.experiment.item.id",+ EXPERIMENT_ITEM_METADATA = "langfuse.experiment.item.metadata",+ EXPERIMENT_ITEM_ROOT_OBSERVATION_ID = "langfuse.experiment.item.root_observation_id",+ EXPERIMENT_ITEM_EXPECTED_OUTPUT = "langfuse.experiment.item.expected_output",}diff --git a/packages/shared/src/server/otel/utils.ts b/packages/shared/src/server/otel/utils.tsindex 20ca5b372c..3487f9bf14 100644--- a/packages/shared/src/server/otel/utils.ts+++ b/packages/shared/src/server/otel/utils.ts@@ -1,3 +1,48 @@export function isValidDateString(dateString: string): boolean {return !isNaN(new Date(dateString).getTime());}++/**+ * Flattens a nested JSON object into path-based names and string values.+ * For example: {foo: {bar: "baz", num: 42}} becomes:+ * - names: ["foo.bar", "foo.num"]+ * - values: ["baz", "42"]+ *+ * All values are converted to strings for consistent storage.+ */+export function flattenJsonToPathArrays(+ obj: Record<string, unknown>,+ prefix: string = "",+): { names: string[]; values: Array<string | null | undefined> } {+ const names: string[] = [];+ const values: Array<string | null | undefined> = [];++ 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 = flattenJsonToPathArrays(+ value as Record<string, unknown>,+ path,+ );+ names.push(...nested.names);+ values.push(...nested.values);+ } else {+ // Leaf value - convert to string+ names.push(path);+ if (value === null || value === undefined || typeof value === "string") {+ values.push(value);+ } else {+ values.push(JSON.stringify(value));+ }+ }+ }++ return { names, values };+}diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex ea86a0ff08..cce671081c 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -15,6 +15,7 @@ export const IngestionEvent = z.object({eventBodyId: z.string(),fileKey: z.string().optional(),skipS3List: z.boolean().optional(),+ forwardToEventsTable: z.boolean().optional(),}),authCheck: z.object({validKey: z.literal(true),diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex fd933cb190..5d5c8d7e73 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -660,7 +660,6 @@ export const eventRecordBaseSchema = z.object({// Generic propsblob_storage_file_path: z.string(),- event_raw: z.string(),event_bytes: z.number(),is_deleted: z.number(),});diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.tsindex 41df794ded..86cfc7b423 100644--- a/packages/shared/src/server/repositories/observations_converters.ts+++ b/packages/shared/src/server/repositories/observations_converters.ts@@ -72,8 +72,11 @@ export const convertObservation = (version: record.version ?? null,input: applyInputOutputRendering(record.input, renderingProps),output: applyInputOutputRendering(record.output, renderingProps),+ // Necessary if we fill this from events as model_parameters will be an objectmodelParameters: record.model_parameters- ? (JSON.parse(record.model_parameters) ?? null)+ ? ((typeof record.model_parameters === "string"+ ? JSON.parse(record.model_parameters)+ : record.model_parameters) ?? null): null,completionStartTime: record.completion_start_time? parseClickhouseUTCDateTimeFormat(record.completion_start_time)diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex c300bca99a..0bbc235b47 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -268,7 +268,6 @@ export const createEvent = (// Generic propsblob_storage_file_path: "",- event_raw: "{}",event_bytes: 2,is_deleted: 0,diff --git a/packages/shared/src/server/utils/compareVersions.ts b/packages/shared/src/server/utils/compareVersions.tsnew file mode 100644index 0000000000..817eb26570--- /dev/null+++ b/packages/shared/src/server/utils/compareVersions.ts@@ -0,0 +1,60 @@+import { z } from "zod/v4";++export const versionSchema = z.string().regex(/^v?\d+\.\d+\.\d+(?:[-+].+)?$/); // e.g. v1.2.3, 1.2.3, v1.2.3-rc.1, v1.2.3+build.123++/**+ * Compare two semantic versions.+ * @param current - Current version (e.g., "v1.2.3")+ * @param latest - Latest/minimum version to compare against (e.g., "v1.2.3")+ * @returns "major" | "minor" | "patch" if latest is newer, null if current >= latest+ */+export const compareVersions = (+ current: string,+ latest: string,+): "major" | "minor" | "patch" | null => {+ const currentValidated = versionSchema.parse(current);+ const latestValidated = versionSchema.parse(latest);++ const parseVersion = (version: string) => {+ if (version.startsWith("v")) {+ version = version.slice(1);+ }+ // Split into version and pre-release parts+ const [versionPart, ...rest] = version.split(/[-+]/);+ const numbers = versionPart.split(".").map(Number);+ return {+ numbers,+ isPreRelease: rest.length > 0,+ };+ };++ const current_parsed = parseVersion(currentValidated);+ const latest_parsed = parseVersion(latestValidated);++ const [currentMajor, currentMinor, currentPatch] = current_parsed.numbers;+ const [latestMajor, latestMinor, latestPatch] = latest_parsed.numbers;++ // If current is a pre-release (RC) and latest is a full release of the same version,+ // consider it as needing a patch update+ if (+ current_parsed.isPreRelease &&+ !latest_parsed.isPreRelease &&+ currentMajor === latestMajor &&+ currentMinor === latestMinor &&+ currentPatch === latestPatch+ ) {+ return "patch";+ }++ if (latestMajor > currentMajor) return "major";+ if (latestMajor === currentMajor && latestMinor > currentMinor)+ return "minor";+ if (+ latestMajor === currentMajor &&+ latestMinor === currentMinor &&+ latestPatch > currentPatch+ )+ return "patch";++ return null;+};diff --git a/web/src/__tests__/async/repositories/event-repository.servertest.ts b/web/src/__tests__/async/repositories/event-repository.servertest.tsindex c2c4382fab..dcf82652f7 100644--- a/web/src/__tests__/async/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/event-repository.servertest.ts@@ -148,7 +148,8 @@ describe("Clickhouse Events Repository Test", () => {const observation = result.find((o) => o.id === generationId);expect(observation).toBeDefined();expect(observation?.id).toBe(generationId);- expect(observation?.internalModelId).toBeNull();+ // Model data should be null or empty string+ expect(observation?.internalModelId || null).toBeNull();expect(observation?.inputPrice).toBeNull();expect(observation?.outputPrice).toBeNull();expect(observation?.totalPrice).toBeNull();diff --git a/web/src/server/api/routers/public.ts b/web/src/server/api/routers/public.tsindex 626b59fe52..4d22d0aa09 100644--- a/web/src/server/api/routers/public.ts+++ b/web/src/server/api/routers/public.ts@@ -1,62 +1,9 @@import { VERSION } from "@/src/constants/VERSION";import { env } from "@/src/env.mjs";import { createTRPCRouter, publicProcedure } from "@/src/server/api/trpc";-import { logger } from "@langfuse/shared/src/server";+import { logger, compareVersions } from "@langfuse/shared/src/server";import { z } from "zod/v4";-const versionSchema = z.string().regex(/^v\d+\.\d+\.\d+(?:[-+].+)?$/); // e.g. v1.2.3, v1.2.3-rc.1, v1.2.3+build.123--const compareVersions = (- current: string,- latest: string,-): "major" | "minor" | "patch" | null => {- const currentValidated = versionSchema.parse(current);- const latestValidated = versionSchema.parse(latest);-- const parseVersion = (version: string) => {- if (version.startsWith("v")) {- version = version.slice(1);- }- // Split into version and pre-release parts- const [versionPart, ...rest] = version.split(/[-+]/);- const numbers = versionPart.split(".").map(Number);- return {- numbers,- isPreRelease: rest.length > 0,- };- };-- const current_parsed = parseVersion(currentValidated);- const latest_parsed = parseVersion(latestValidated);-- const [currentMajor, currentMinor, currentPatch] = current_parsed.numbers;- const [latestMajor, latestMinor, latestPatch] = latest_parsed.numbers;-- // If current is a pre-release (RC) and latest is a full release of the same version,- // consider it as needing a patch update- if (- current_parsed.isPreRelease &&- !latest_parsed.isPreRelease &&- currentMajor === latestMajor &&- currentMinor === latestMinor &&- currentPatch === latestPatch- ) {- return "patch";- }-- if (latestMajor > currentMajor) return "major";- if (latestMajor === currentMajor && latestMinor > currentMinor)- return "minor";- if (- latestMajor === currentMajor &&- latestMinor === currentMinor &&- latestPatch > currentPatch- )- return "patch";-- return null;-};-const ReleaseApiRes = z.array(z.object({repo: z.string(),diff --git a/worker/src/app.ts b/worker/src/app.tsindex 9da794688b..45756e9c8a 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -489,7 +489,10 @@ if (env.QUEUE_CONSUMER_ENTITY_CHANGE_QUEUE_IS_ENABLED === "true") {);}-if (env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true") {+if (+ env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true" &&+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+) {// Instantiate the queue to trigger scheduled jobsEventPropagationQueue.getInstance();diff --git a/worker/src/backgroundMigrations/backfillEventsHistoric.ts b/worker/src/backgroundMigrations/backfillEventsHistoric.tsindex f21ad6ea41..875f855049 100644--- a/worker/src/backgroundMigrations/backfillEventsHistoric.ts+++ b/worker/src/backgroundMigrations/backfillEventsHistoric.ts@@ -287,7 +287,6 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {telemetry_sdk_name,telemetry_sdk_version,blob_storage_file_path,- event_raw,event_bytes,created_at,updated_at,@@ -317,7 +316,7 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {o.completion_start_time,o.prompt_id,o.prompt_name,- CAST(o.prompt_version, 'Nullable(String)') AS prompt_version,+ o.prompt_version,o.internal_model_id AS model_id,o.provided_model_name,o.model_parameters,@@ -340,7 +339,6 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {NULL AS telemetry_sdk_name,NULL AS telemetry_sdk_version,'' AS blob_storage_file_path,- '' AS event_raw,byteSize(*) AS event_bytes,o.created_at,o.updated_at,diff --git a/worker/src/env.ts b/worker/src/env.tsindex 06fce3d1b4..c6291775b1 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -234,6 +234,14 @@ const EnvSchema = z.object({.number().positive().default(10),+ LANGFUSE_DATASET_RUN_BACKFILL_CHUNK_SIZE: z.coerce+ .number()+ .positive()+ .default(200),+ LANGFUSE_EXPERIMENT_BACKFILL_THROTTLE_MS: z.coerce+ .number()+ .positive()+ .default(5 * 60 * 1000), // 5 minutes// Core data S3 upload - Langfuse CloudLANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED: zdiff --git a/worker/src/features/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.tsindex e47764ae76..981d17e263 100644--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts@@ -217,6 +217,13 @@ export const handleEventPropagationJob = async (max(start_time) as max_start_timefrom observations_batch_stagingwhere _partition_value = tuple('${partitionToProcess}')+ ), experiment_traces_to_exclude as (+ select distinct+ project_id,+ trace_id+ from dataset_run_items_rmt+ where project_id in (select arrayJoin(project_ids) from batch_stats)+ and created_at >= now() - interval 24 hour), relevant_traces as (selectt.id,@@ -280,7 +287,6 @@ export const handleEventPropagationJob = async (telemetry_sdk_name,telemetry_sdk_version,blob_storage_file_path,- event_raw,event_bytes,created_at,updated_at,@@ -312,7 +318,7 @@ export const handleEventPropagationJob = async (obs.completion_start_time,obs.prompt_id,obs.prompt_name,- CAST(obs.prompt_version, 'Nullable(String)') AS prompt_version,+ obs.prompt_version,obs.internal_model_id AS model_id,obs.provided_model_name,obs.model_parameters,@@ -342,7 +348,6 @@ export const handleEventPropagationJob = async (NULL AS telemetry_sdk_name,NULL AS telemetry_sdk_version,'' AS blob_storage_file_path,- '' AS event_raw,byteSize(*) AS event_bytes,obs.created_at,obs.updated_at,@@ -354,6 +359,11 @@ export const handleEventPropagationJob = async (obs.project_id = t.project_id ANDobs.trace_id = t.id)+ LEFT ANTI JOIN experiment_traces_to_exclude excl+ ON (+ excl.project_id = obs.project_id AND+ excl.trace_id = obs.trace_id+ )WHERE obs._partition_value = tuple('${partitionToProcess}')`,tags: {diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.tsnew file mode 100644index 0000000000..beff362529--- /dev/null+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts@@ -0,0 +1,762 @@+import {+ logger,+ queryClickhouse,+ redis,+ convertDateToClickhouseDateTime,+ clickhouseClient,+ flattenJsonToPathArrays,+} from "@langfuse/shared/src/server";+import { env } from "../../env";+import { ClickhouseWriter } from "../../services/ClickhouseWriter";+import { IngestionService } from "../../services/IngestionService";+import { prisma } from "@langfuse/shared/src/db";++const EXPERIMENT_BACKFILL_TIMESTAMP_KEY =+ "langfuse:event-propagation:experiment-backfill:last-run";++interface DatasetRunItem {+ id: string;+ project_id: string;+ trace_id: string;+ observation_id: string | null;+ dataset_run_id: string;+ dataset_run_name: string;+ dataset_run_description: string;+ dataset_run_metadata: Record<string, unknown>;+ dataset_id: string;+ dataset_item_id: string;+ dataset_item_expected_output: string;+ dataset_item_metadata: Record<string, unknown>;+ created_at: string;+}++interface SpanRecord {+ project_id: string;+ trace_id: string;+ span_id: string;+ parent_span_id: string;+ start_time: string;+ end_time: string | null;+ name: string;+ type: string;+ environment: string;+ version: string;+ input: string;+ output: string;+ // Add other fields as needed from observations/traces+ level: string;+ status_message: string;+ completion_start_time: string | null;+ prompt_id: string;+ prompt_name: string;+ prompt_version: string | null;+ model_id: string;+ provided_model_name: string;+ model_parameters: string;+ provided_usage_details: Record<string, number> | null;+ usage_details: Record<string, number> | null;+ provided_cost_details: Record<string, number> | null;+ cost_details: Record<string, number> | null;+ total_cost: number;+ metadata: Record<string, unknown>;+ user_id: string;+ session_id: string;+}++interface EnrichedSpan extends SpanRecord {+ experiment_id: string;+ experiment_name: string;+ experiment_metadata_names: string[];+ experiment_metadata_values: Array<string | null | undefined>;+ experiment_description: string;+ experiment_dataset_id: string;+ experiment_item_id: string;+ experiment_item_root_span_id: string;+ experiment_item_expected_output: string;+ experiment_item_metadata_names: string[];+ experiment_item_metadata_values: Array<string | null | undefined>;+}++/**+ * Fetch dataset run items created within a time window.+ * Deduplicates by (project_id, trace_id, observation_id) taking the most recent.+ */+export async function getDatasetRunItemsSinceLastRun(+ lastRun: Date,+ upperBound: Date,+): Promise<DatasetRunItem[]> {+ const query = `+ WITH prefiltered_events as (+ select distinct project_id, trace_id+ from events+ where start_time > {lastRun: DateTime64(3)} - interval 1 day+ and project_id in (+ select distinct project_id+ from dataset_run_items_rmt+ where created_at > {lastRun: DateTime64(3)}+ )+ )++ SELECT+ dri.id,+ dri.project_id,+ dri.trace_id,+ dri.observation_id,+ dri.dataset_run_id,+ dri.dataset_run_name,+ dri.dataset_run_description,+ dri.dataset_run_metadata,+ dri.dataset_id,+ dri.dataset_item_id,+ dri.dataset_item_expected_output,+ dri.dataset_item_metadata,+ dri.created_at+ FROM dataset_run_items_rmt AS dri+ LEFT ANTI JOIN prefiltered_events AS pe+ ON dri.project_id = pe.project_id+ AND dri.trace_id = pe.trace_id+ WHERE dri.created_at > {lastRun: DateTime64(3)}+ AND dri.created_at <= {upperBound: DateTime64(3)}+ ORDER BY dri.created_at DESC+ LIMIT 1 BY dri.project_id, dri.trace_id, coalesce(dri.observation_id, '')+ `;++ const rows = await queryClickhouse<DatasetRunItem>({+ query,+ params: {+ lastRun: convertDateToClickhouseDateTime(lastRun),+ upperBound: convertDateToClickhouseDateTime(upperBound),+ },+ tags: {+ feature: "experiment-backfill",+ operation_name: "getDatasetRunItemsSinceLastRun",+ },+ });++ logger.info(+ `[EXPERIMENT BACKFILL] Found ${rows.length} dataset run items between ${lastRun.toISOString()} and ${upperBound.toISOString()}`,+ );++ return rows;+}++/**+ * Fetch observations that belong to traces referenced by dataset run items.+ */+export async function getRelevantObservations(+ projectIds: string[],+ traceIds: string[],+ minTime: Date,+): Promise<SpanRecord[]> {+ if (projectIds.length === 0 || traceIds.length === 0) {+ return [];+ }++ const query = `+ SELECT+ o.project_id,+ o.trace_id,+ o.id AS span_id,+ CASE+ WHEN o.id = concat('t-', o.trace_id) THEN ''+ ELSE coalesce(o.parent_observation_id, concat('t-', o.trace_id))+ END AS parent_span_id,+ greatest(o.start_time, toDateTime64('1970-01-01', 3)) AS start_time,+ o.end_time AS end_time,+ o.name,+ o.type,+ coalesce(o.environment, '') AS environment,+ coalesce(o.version, '') AS version,+ coalesce(o.input, '') AS input,+ coalesce(o.output, '') AS output,+ o.level AS level,+ coalesce(o.status_message, '') AS status_message,+ o.completion_start_time AS completion_start_time,+ coalesce(o.prompt_id, '') AS prompt_id,+ coalesce(o.prompt_name, '') AS prompt_name,+ o.prompt_version AS prompt_version,+ coalesce(o.internal_model_id, '') AS model_id,+ coalesce(o.provided_model_name, '') AS provided_model_name,+ coalesce(o.model_parameters, '') AS model_parameters,+ o.provided_usage_details AS provided_usage_details,+ o.usage_details AS usage_details,+ o.provided_cost_details AS provided_cost_details,+ o.cost_details AS cost_details,+ coalesce(o.total_cost, 0) AS total_cost,+ o.metadata,+ '' AS user_id,+ '' AS session_id+ FROM observations o+ WHERE o.project_id IN {projectIds: Array(String)}+ AND o.trace_id IN {traceIds: Array(String)}+ AND o.start_time >= {minTime: DateTime64(3)} - interval 4 hour+ ORDER BY o.event_ts DESC+ LIMIT 1 BY o.project_id, o.id+ `;++ return queryClickhouse<SpanRecord>({+ query,+ params: {+ projectIds,+ traceIds,+ minTime: convertDateToClickhouseDateTime(minTime),+ },+ tags: {+ feature: "experiment-backfill",+ operation_name: "getRelevantObservations",+ },+ });+}++/**+ * Fetch traces that are referenced by dataset run items.+ */+export async function getRelevantTraces(+ projectIds: string[],+ traceIds: string[],+ minTime: Date,+): Promise<SpanRecord[]> {+ if (projectIds.length === 0 || traceIds.length === 0) {+ return [];+ }++ const query = `+ SELECT+ t.project_id,+ t.id AS trace_id,+ concat('t-', t.id) AS span_id,+ '' AS parent_span_id,+ t.timestamp AS start_time,+ '' AS end_time,+ coalesce(t.name, '') AS name,+ 'SPAN' AS type,+ coalesce(t.environment, '') AS environment,+ coalesce(t.version, '') AS version,+ coalesce(t.input, '') AS input,+ coalesce(t.output, '') AS output,+ '' AS level,+ '' AS status_message,+ '' AS completion_start_time,+ '' AS prompt_id,+ '' AS prompt_name,+ '' AS prompt_version,+ '' AS model_id,+ '' AS provided_model_name,+ '' AS model_parameters,+ map() AS provided_usage_details,+ map() AS usage_details,+ map() AS provided_cost_details,+ map() AS cost_details,+ 0 AS total_cost,+ t.metadata,+ coalesce(t.user_id, '') AS user_id,+ coalesce(t.session_id, '') AS session_id+ FROM traces t+ WHERE t.project_id IN {projectIds: Array(String)}+ AND t.id IN {traceIds: Array(String)}+ AND t.timestamp >= {minTime: DateTime64(3)} - interval 4 hour+ ORDER BY t.event_ts DESC+ LIMIT 1 BY t.project_id, t.id+ `;++ return queryClickhouse<SpanRecord>({+ query,+ params: {+ projectIds,+ traceIds,+ minTime: convertDateToClickhouseDateTime(minTime),+ },+ tags: {+ feature: "experiment-backfill",+ operation_name: "getRelevantTraces",+ },+ });+}++/**+ * Build span and child maps for efficient lookups and tree traversal.+ */+export function buildSpanMaps(spans: SpanRecord[]): {+ spanMap: Map<string, SpanRecord>;+ childMap: Map<string, SpanRecord[]>;+} {+ const spanMap = new Map<string, SpanRecord>();+ const childMap = new Map<string, SpanRecord[]>();++ for (const span of spans) {+ spanMap.set(span.span_id, span);++ // Add to parent's children list+ const parentId = span.parent_span_id;+ if (!childMap.has(parentId)) {+ childMap.set(parentId, []);+ }+ childMap.get(parentId)!.push(span);+ }++ return { spanMap, childMap };+}++/**+ * Recursively find all child spans for a given root span.+ */+export function findAllChildren(+ rootSpanId: string,+ childMap: Map<string, SpanRecord[]>,+): SpanRecord[] {+ const children: SpanRecord[] = [];+ const queue: string[] = [rootSpanId];++ while (queue.length > 0) {+ const currentId = queue.shift()!;+ const directChildren = childMap.get(currentId) || [];++ for (const child of directChildren) {+ children.push(child);+ queue.push(child.span_id);+ }+ }++ return children;+}++/**+ * Convert a SpanRecord to EnrichedSpan format with empty experiment fields.+ * Used for spans that are not part of any dataset run item but should still be included in events.+ */+function convertToEnrichedSpanWithoutExperiment(+ span: SpanRecord,+): EnrichedSpan {+ return {+ ...span,+ experiment_id: "",+ experiment_name: "",+ experiment_metadata_names: [],+ experiment_metadata_values: [],+ experiment_description: "",+ experiment_dataset_id: "",+ experiment_item_id: "",+ experiment_item_root_span_id: "",+ experiment_item_expected_output: "",+ experiment_item_metadata_names: [],+ experiment_item_metadata_values: [],+ };+}++/**+ * Enrich spans with experiment properties from dataset run item.+ * Also propagates trace-level properties (userId, sessionId) to all child spans.+ */+export function enrichSpansWithExperiment(+ rootSpan: SpanRecord,+ childSpans: SpanRecord[],+ dri: DatasetRunItem,+ traceProperties: { userId: string; sessionId: string },+): EnrichedSpan[] {+ const enrichedSpans: EnrichedSpan[] = [];++ const experimentMetadataFlattened = flattenJsonToPathArrays(+ dri.dataset_run_metadata,+ );+ const experimentItemMetadataFlattened = flattenJsonToPathArrays(+ dri.dataset_item_metadata,+ );++ // Enrich root span+ enrichedSpans.push({+ ...rootSpan,+ user_id: traceProperties.userId,+ session_id: traceProperties.sessionId,+ experiment_id: dri.dataset_run_id,+ experiment_name: dri.dataset_run_name,+ experiment_metadata_names: experimentMetadataFlattened.names,+ experiment_metadata_values: experimentMetadataFlattened.values,+ experiment_description: dri.dataset_run_description,+ experiment_dataset_id: dri.dataset_id,+ experiment_item_id: dri.dataset_item_id,+ experiment_item_root_span_id: rootSpan.span_id,+ experiment_item_expected_output: dri.dataset_item_expected_output,+ experiment_item_metadata_names: experimentItemMetadataFlattened.names,+ experiment_item_metadata_values: experimentItemMetadataFlattened.values,+ });++ // Enrich child spans+ for (const child of childSpans) {+ enrichedSpans.push({+ ...child,+ user_id: traceProperties.userId,+ session_id: traceProperties.sessionId,+ experiment_id: dri.dataset_run_id,+ experiment_name: dri.dataset_run_name,+ experiment_metadata_names: experimentMetadataFlattened.names,+ experiment_metadata_values: experimentMetadataFlattened.values,+ experiment_description: dri.dataset_run_description,+ experiment_dataset_id: dri.dataset_id,+ experiment_item_id: dri.dataset_item_id,+ experiment_item_root_span_id: rootSpan.span_id,+ experiment_item_expected_output: dri.dataset_item_expected_output,+ experiment_item_metadata_names: experimentItemMetadataFlattened.names,+ experiment_item_metadata_values: experimentItemMetadataFlattened.values,+ });+ }++ return enrichedSpans;+}++/**+ * Write enriched spans to the events table using IngestionService.writeEvent().+ * Converts EnrichedSpan to EventInput format.+ */+async function writeEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {+ if (spans.length === 0) {+ return;+ }++ // Ensure required dependencies are available+ if (!redis) throw new Error("Redis not available");+ if (!prisma) throw new Error("Prisma not available");++ const ingestionService = new IngestionService(+ redis,+ prisma,+ ClickhouseWriter.getInstance(),+ clickhouseClient(),+ );++ for (const span of spans) {+ // Convert EnrichedSpan to EventInput format+ const eventInput = {+ // Required identifiers+ projectId: span.project_id,+ traceId: span.trace_id,+ spanId: span.span_id,+ startTimeISO: span.start_time,+ endTimeISO: span.end_time || span.start_time, // Required field, use start_time as fallback++ // Optional identifiers+ parentSpanId: span.parent_span_id || undefined,++ // Core properties+ name: span.name,+ type: span.type,+ environment: span.environment || undefined,+ version: span.version || undefined,+ completionStartTime: span.completion_start_time || undefined,++ // User/session+ userId: span.user_id || undefined,+ sessionId: span.session_id || undefined,+ level: span.level || undefined,+ statusMessage: span.status_message || undefined,++ // Prompt+ promptId: span.prompt_id || undefined,+ promptName: span.prompt_name || undefined,+ promptVersion: span.prompt_version || undefined,++ // Model+ modelName: span.provided_model_name || undefined,+ modelParameters: span.model_parameters || undefined,++ // Usage & Cost+ providedUsageDetails: span.provided_usage_details || undefined,+ usageDetails: span.usage_details || undefined,+ providedCostDetails: span.provided_cost_details || undefined,+ costDetails: span.cost_details || undefined,+ totalCost: span.total_cost || undefined,++ // I/O+ input: span.input || undefined,+ output: span.output || undefined,++ // Metadata+ metadata: span.metadata,++ // Source/instrumentation+ source: "ingestion-api",++ // Experiment fields+ experimentId: span.experiment_id,+ experimentName: span.experiment_name,+ experimentMetadataNames: span.experiment_metadata_names,+ experimentMetadataValues: span.experiment_metadata_values,+ experimentDescription: span.experiment_description,+ experimentDatasetId: span.experiment_dataset_id,+ experimentItemId: span.experiment_item_id,+ experimentItemRootSpanId: span.experiment_item_root_span_id,+ experimentItemExpectedOutput: span.experiment_item_expected_output,+ experimentItemMetadataNames: span.experiment_item_metadata_names,+ experimentItemMetadataValues: span.experiment_item_metadata_values,+ };++ await ingestionService.writeEvent(eventInput, ""); // Empty fileKey since we're not storing raw events+ }++ logger.info(+ `[EXPERIMENT BACKFILL] Wrote ${spans.length} enriched spans to events table via IngestionService`,+ );+}++/**+ * Initialize the experiment backfill cutoff timestamp if not already set.+ * Uses Redis SET NX to ensure we don't backfill historical data on first run.+ *+ * @returns The cutoff timestamp to use for backfill queries+ */+export async function initializeBackfillCutoff(): Promise<Date> {+ if (!redis) {+ logger.error(+ "[EXPERIMENT BACKFILL] Redis not available, using current time as cutoff",+ );+ throw new Error(+ "Redis not available. Experiment backfill cannot be initialized.",+ );+ }++ try {+ const now = new Date().toISOString();++ // Try to set the key only if it doesn't exist (NX)+ const result = await redis.set(+ EXPERIMENT_BACKFILL_TIMESTAMP_KEY,+ now,+ "NX",+ );++ if (result === "OK") {+ logger.info(+ `[EXPERIMENT BACKFILL] Initialized cutoff timestamp to ${now} (first run)`,+ );+ return new Date(now);+ }++ // Key already exists, fetch the existing value+ const existing = await redis.get(EXPERIMENT_BACKFILL_TIMESTAMP_KEY);+ if (existing) {+ logger.debug(+ `[EXPERIMENT BACKFILL] Using existing cutoff timestamp: ${existing}`,+ );+ return new Date(existing);+ }++ // Fallback if something went wrong+ logger.warn(+ "[EXPERIMENT BACKFILL] Could not read existing timestamp, using current time",+ );+ return new Date();+ } catch (error) {+ logger.error(+ "[EXPERIMENT BACKFILL] Failed to initialize cutoff timestamp",+ error,+ );+ return new Date();+ }+}++/**+ * Check if the experiment backfill should run based on the throttle.+ * (Default every 5min).+ *+ * @returns true if backfill should run (>5min since last run), false otherwise+ */+export async function shouldRunBackfill(lastRun: Date): Promise<boolean> {+ const now = new Date();+ const timeSinceLastRun = now.getTime() - lastRun.getTime();+ return timeSinceLastRun >= env.LANGFUSE_EXPERIMENT_BACKFILL_THROTTLE_MS;+}++/**+ * Update the experiment backfill timestamp after successful execution.+ * @param timestamp The timestamp to set (should be the upper bound used for the backfill)+ */+export async function updateBackfillTimestamp(timestamp: Date): Promise<void> {+ if (!redis) {+ logger.warn(+ "[EXPERIMENT BACKFILL] Redis not available, cannot update timestamp",+ );+ return;+ }++ try {+ const timestampStr = timestamp.toISOString();+ await redis.set(EXPERIMENT_BACKFILL_TIMESTAMP_KEY, timestampStr);+ logger.info(+ `[EXPERIMENT BACKFILL] Updated last run timestamp to ${timestampStr}`,+ );+ } catch (error) {+ logger.error("[EXPERIMENT BACKFILL] Failed to update timestamp", error);+ }+}++/**+ * Chunk an array into smaller arrays of specified size.+ */+function chunk<T>(array: T[], size: number): T[][] {+ const chunks: T[][] = [];+ for (let i = 0; i < array.length; i += size) {+ chunks.push(array.slice(i, i + size));+ }+ return chunks;+}++/**+ * Main entry point for experiment backfill.+ * Handles initialization, throttle checking, execution, and timestamp updates.+ */+export async function runExperimentBackfill(): Promise<void> {+ logger.info("[EXPERIMENT BACKFILL] Checking if backfill should run");++ try {+ // Initialize cutoff timestamp (first-run protection)+ const lastRun = await initializeBackfillCutoff();++ // Check 5-minute throttle+ if (!(await shouldRunBackfill(lastRun))) {+ logger.debug("[EXPERIMENT BACKFILL] Skipping due to throttle");+ return;+ }++ // Calculate upper bound (now - 30s) to avoid race conditions+ // This ensures we don't process items that might still be receiving data+ const upperBound = new Date(Date.now() - 30 * 1000);++ // Execute backfill+ logger.info("[EXPERIMENT BACKFILL] Starting backfill process");+ await processExperimentBackfill(lastRun, upperBound);++ // Update timestamp with the upper bound we processed up to+ await updateBackfillTimestamp(upperBound);+ logger.info("[EXPERIMENT BACKFILL] Backfill completed successfully");+ } catch (error) {+ logger.error("[EXPERIMENT BACKFILL] Failed to run backfill", error);+ throw error;+ }+}++/**+ * Internal orchestration function to process experiment backfill.+ */+async function processExperimentBackfill(+ lastRun: Date,+ upperBound: Date,+): Promise<void> {+ logger.info(+ `[EXPERIMENT BACKFILL] Starting backfill process with lastRun ${lastRun.toISOString()} and upperBound ${upperBound.toISOString()}`,+ );++ // Step 1: Fetch dataset run items within time window [lastRun, upperBound]+ const allDatasetRunItems = await getDatasetRunItemsSinceLastRun(+ lastRun,+ upperBound,+ );++ if (allDatasetRunItems.length === 0) {+ logger.info(+ "[EXPERIMENT BACKFILL] No dataset run items to process, skipping",+ );+ return;+ }++ // Step 2: Process in chunks+ const chunkSize = env.LANGFUSE_DATASET_RUN_BACKFILL_CHUNK_SIZE;+ const chunks = chunk(allDatasetRunItems, chunkSize);++ logger.info(+ `[EXPERIMENT BACKFILL] Processing ${allDatasetRunItems.length} items in ${chunks.length} chunks of ${chunkSize}`,+ );++ for (let i = 0; i < chunks.length; i++) {+ const driChunk = chunks[i];+ logger.info(+ `[EXPERIMENT BACKFILL] Processing chunk ${i + 1}/${chunks.length} with ${driChunk.length} items`,+ );++ // Extract project and trace IDs for this chunk+ const projectIds = [...new Set(driChunk.map((dri) => dri.project_id))];+ const traceIds = [...new Set(driChunk.map((dri) => dri.trace_id))];++ // Fetch observations and traces+ const [observations, traces] = await Promise.all([+ getRelevantObservations(projectIds, traceIds, lastRun),+ getRelevantTraces(projectIds, traceIds, lastRun),+ ]);++ logger.info(+ `[EXPERIMENT BACKFILL] Fetched ${observations.length} observations and ${traces.length} traces`,+ );++ // Combine spans+ const allSpans = [...observations, ...traces];+ 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 }+ >();+ for (const trace of traces) {+ tracePropertiesMap.set(trace.trace_id, {+ userId: trace.user_id,+ sessionId: trace.session_id,+ });+ }++ // Process each dataset run item+ const allEnrichedSpans: EnrichedSpan[] = [];+ const processedSpanIds = new Set<string>();++ for (const dri of driChunk) {+ // Find the root span (either observation or trace)+ const rootSpanId = dri.observation_id || `t-${dri.trace_id}`;+ const rootSpan = spanMap.get(rootSpanId);++ if (!rootSpan) {+ logger.warn(+ `[EXPERIMENT BACKFILL] Root span ${rootSpanId} not found for DRI ${dri.id}, skipping`,+ );+ continue;+ }++ // Get trace-level properties for this trace+ const traceProperties = tracePropertiesMap.get(dri.trace_id) || {+ userId: "",+ sessionId: "",+ };++ // Find all children recursively+ const childSpans = findAllChildren(rootSpanId, childMap);++ // Enrich spans with experiment properties and propagate trace-level properties+ const enrichedSpans = enrichSpansWithExperiment(+ rootSpan,+ childSpans,+ dri,+ traceProperties,+ );++ allEnrichedSpans.push(...enrichedSpans);++ // Track which spans have been processed+ processedSpanIds.add(rootSpan.span_id);+ for (const child of childSpans) {+ processedSpanIds.add(child.span_id);+ }+ }++ // 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));+ }+ }++ // Write enriched spans to events table+ if (allEnrichedSpans.length > 0) {+ await writeEnrichedSpans(allEnrichedSpans);+ }+ }++ logger.info(+ `[EXPERIMENT BACKFILL] Completed backfill process for ${allDatasetRunItems.length} items`,+ );+}diff --git a/worker/src/queues/eventPropagationQueue.ts b/worker/src/queues/eventPropagationQueue.tsindex d8a553240f..32d827b55a 100644--- a/worker/src/queues/eventPropagationQueue.ts+++ b/worker/src/queues/eventPropagationQueue.ts@@ -5,6 +5,7 @@ import {instrumentAsync,} from "@langfuse/shared/src/server";import { handleEventPropagationJob } from "../features/eventPropagation/handleEventPropagationJob";+import { runExperimentBackfill } from "../features/eventPropagation/handleExperimentBackfill";import { SpanKind } from "@opentelemetry/api";export const eventPropagationProcessor: Processor = async (job) => {@@ -18,7 +19,10 @@ export const eventPropagationProcessor: Processor = async (job) => {async () => {logger.info("Executing Event Propagation Job");try {- return await handleEventPropagationJob(job);+ // Step 1: Execute the main partition processing+ await handleEventPropagationJob(job);+ // Step 2: Execute experiment backfill with 5-minute throttle+ await runExperimentBackfill();} catch (error) {logger.error("Error executing EventPropagationJob", error);throw error;diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsindex 33b4a87bb7..afda96f7e1 100644--- a/worker/src/queues/ingestionQueue.ts+++ b/worker/src/queues/ingestionQueue.ts@@ -251,6 +251,14 @@ export const ingestionQueueProcessorBuilder = (if (!redis) throw new Error("Redis not available");if (!prisma) throw new Error("Prisma not available");+ // Determine whether to forward to staging events table+ // Use explicit flag from job payload if provided, otherwise fall back to env flags+ const forwardToEventsTable =+ job.data.payload.data.forwardToEventsTable ??+ (env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" &&+ env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true" &&+ env.LANGFUSE_EXPERIMENT_EARLY_EXIT_EVENT_BATCH_JOB !== "true");+await new IngestionService(redis,prisma,@@ -262,11 +270,7 @@ export const ingestionQueueProcessorBuilder = (job.data.payload.data.eventBodyId,firstS3WriteTime,events,- // Should be true eventually, but depends on feature flag in the meantime.- // writeToStagingTables - enables batch propagation to events table- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" &&- env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true" &&- env.LANGFUSE_EXPERIMENT_EARLY_EXIT_EVENT_BATCH_JOB !== "true",+ forwardToEventsTable,);} catch (e) {logger.error(diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex 476e99683d..09899c3cff 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -16,6 +16,8 @@ import {redis,TQueueJobTypes,traceException,+ compareVersions,+ ResourceSpan,} from "@langfuse/shared/src/server";import { env } from "../env";import { IngestionService } from "../services/IngestionService";@@ -23,6 +25,89 @@ import { prisma } from "@langfuse/shared/src/db";import { ClickhouseWriter } from "../services/ClickhouseWriter";import { ForbiddenError } from "@langfuse/shared";+/**+ * SDK information extracted from OTEL resourceSpans.+ */+type SdkInfo = {+ scopeName: string | null;+ scopeVersion: string | null;+ telemetrySdkLanguage: string | null;+};++/**+ * Extract SDK information from resourceSpans.+ * Gets scope name/version and telemetry SDK language from the OTEL structure.+ */+function getSdkInfoFromResourceSpans(resourceSpans: ResourceSpan): SdkInfo {+ try {+ // Get the first scopeSpan (all spans in a batch share the same scope)+ const firstScopeSpan = resourceSpans?.scopeSpans?.[0];+ const scopeName = firstScopeSpan?.scope?.name ?? null;+ const scopeVersion = firstScopeSpan?.scope?.version ?? null;++ // Extract telemetry SDK language from resource attributes+ const resourceAttributes = resourceSpans?.resource?.attributes ?? [];+ const telemetrySdkLanguage =+ resourceAttributes.find((attr) => attr.key === "telemetry.sdk.language")+ ?.value?.stringValue ?? null;++ return { scopeName, scopeVersion, telemetrySdkLanguage };+ } catch (error) {+ logger.warn("Failed to extract SDK info from resourceSpans", error);+ return { scopeName: null, scopeVersion: null, telemetrySdkLanguage: null };+ }+}++/**+ * Check if SDK meets version requirements for direct event writes.+ *+ * Requirements:+ * - Scope name must contain 'langfuse' (case-insensitive)+ * - Python SDK: scope_version >= 3.9.0+ * - JS/JavaScript SDK: scope_version >= 4.4.0+ */+function checkSdkVersionRequirements(+ sdkInfo: SdkInfo,+ isSdkExperimentBatch: boolean,+): boolean {+ const { scopeName, scopeVersion, telemetrySdkLanguage } = sdkInfo;++ // Must be a Langfuse SDK+ if (!scopeName || !String(scopeName).toLowerCase().includes("langfuse")) {+ return false;+ }++ if (!scopeVersion || !telemetrySdkLanguage) {+ return false;+ }++ try {+ // Python SDK >= 3.9.0+ if (telemetrySdkLanguage === "python" && isSdkExperimentBatch) {+ const comparison = compareVersions(scopeVersion, "v3.9.0");+ return comparison === null; // null means current >= latest+ }++ // JS/JavaScript SDK >= 4.4.0+ if (+ (telemetrySdkLanguage === "js" ||+ telemetrySdkLanguage === "javascript") &&+ isSdkExperimentBatch+ ) {+ const comparison = compareVersions(scopeVersion, "v4.4.0");+ return comparison === null; // null means current >= latest+ }++ return false;+ } catch (error) {+ logger.warn(+ `Failed to parse SDK version ${scopeVersion} for language ${telemetrySdkLanguage}`,+ error,+ );+ return false;+ }+}+export const otelIngestionQueueProcessor: Processor = async (job: Job<TQueueJobTypes[QueueName.OtelIngestionQueue]>,): Promise<void> => {@@ -118,13 +203,44 @@ export const otelIngestionQueueProcessor: Processor = async (clickhouseClient(),);+ // Decide whether observations should be processed via new flow (directly to events table)+ // or via the dual write (staging table and batch job to events).+ // Rules:+ // 1. If the environment is `sdk-experiment`, JS SDK 4.4.0+ and python SDK 3.9.0+ will write directly to events.+ // 2. All other observations will go through the dual write until we have SDKs in place that have old trace updates+ // deprecated and new methods in place.+ // 3. Non-Langfuse SDK spans will go through the dual write until a yet to be determined cutoff date.+ // Check if any observation has environment='sdk-experiment'+ const hasExperimentEnvironment = observations.some((o) => {+ const body = o.body as { environment?: string };+ return body.environment === "sdk-experiment";+ });+ const sdkInfo =+ parsedSpans.length > 0+ ? getSdkInfoFromResourceSpans(parsedSpans[0])+ : { scopeName: null, scopeVersion: null, telemetrySdkLanguage: null };+ const useDirectEventWrite = checkSdkVersionRequirements(+ sdkInfo,+ hasExperimentEnvironment,+ );++ const shouldForwardToEventsTable =+ !useDirectEventWrite &&+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" &&+ env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true" &&+ env.LANGFUSE_EXPERIMENT_EARLY_EXIT_EVENT_BATCH_JOB !== "true";+// Running everything concurrently might be detrimental to the event loop, but has probably// the highest possible throughput. Therefore, we start with a Promise.all.// If necessary, we may use a for each instead.await Promise.all([// Process traces- processEventBatch(traces, auth, { delay: 0, source: "otel" }),+ processEventBatch(traces, auth, {+ delay: 0,+ source: "otel",+ forwardToEventsTable: shouldForwardToEventsTable,+ }),// Process observationsobservations.map((observation) =>ingestionService.mergeAndWrite(@@ -133,16 +249,18 @@ export const otelIngestionQueueProcessor: Processor = async (observation.body.id || "", // id is always defined for observationsnew Date(), // Use the current timestamp as event time[observation],- // TODO: Eventually we want to set this one to true, but then skip the event processing below and vice versa- false,+ shouldForwardToEventsTable,),),].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") {+ // If inserts into the events table are enabled AND observations qualify for direct write,+ // 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" &&+ useDirectEventWrite+ ) {try {const events = processor.processToEvent(parsedSpans);await Promise.all(diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 9373b26b1c..27c31b3e26 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -43,6 +43,7 @@ import {EventRecordInsertType,hasNoJobConfigsCache,traceException,+ flattenJsonToPathArrays,} from "@langfuse/shared/src/server";import { tokenCountAsync } from "../../features/tokenisation/async-usage";@@ -101,7 +102,7 @@ export type EventInput = {// ModelmodelName?: string;- modelParameters?: string;+ modelParameters?: string | Record<string, unknown>;// Usage & CostprovidedUsageDetails?: Record<string, number>;@@ -133,6 +134,19 @@ export type EventInput = {eventRaw?: string;eventBytes?: number;+ // Experiment fields+ experimentId?: string;+ experimentName?: string;+ experimentMetadataNames?: string[];+ experimentMetadataValues?: Array<string | null | undefined>;+ experimentDescription?: string;+ experimentDatasetId?: string;+ experimentItemId?: string;+ experimentItemRootSpanId?: string;+ experimentItemExpectedOutput?: string;+ experimentItemMetadataNames?: string[];+ experimentItemMetadataValues?: Array<string | null | undefined>;+// Catch-all for future fields[key: string]: any;};@@ -270,7 +284,7 @@ export class IngestionService {const metadata = eventData.metadata;// Flatten to path-based arrays- const flattened = this.flattenJsonToPathArrays(metadata);+ const flattened = flattenJsonToPathArrays(metadata);const metadataNames = flattened.names;const metadataValues = flattened.values;@@ -322,7 +336,11 @@ export class IngestionService {// Model// model_id: eventData.modelId,provided_model_name: eventData.modelName,- model_parameters: eventData.modelParameters,+ model_parameters: eventData.modelParameters+ ? typeof eventData.modelParameters === "string"+ ? JSON.parse(eventData.modelParameters)+ : eventData.modelParameters+ : {},// Usage & Cost// provided_usage_details: eventData.providedUsageDetails ?? {},@@ -358,9 +376,21 @@ export class IngestionService {// Storageblob_storage_file_path: fileKey,- // event_raw: eventData.eventRaw ?? "",event_bytes: eventData.eventBytes ?? 0,+ // Experiment fields+ experiment_id: eventData.experimentId,+ experiment_name: eventData.experimentName,+ 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,+// System timestampscreated_at: now,updated_at: now,@@ -1618,97 +1648,6 @@ export class IngestionService {// Otherwise, use the current timestamp to avoid updating old partitionsreturn ageInMs < threeAndHalfMinutesInMs ? createdAt : 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">;