🪢 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
feat(worker): V4 self-hosted historic backfill chain (#13623)
Steffen Schmitza6e3613fcc1f
diff --git a/.env.dev.example b/.env.dev.exampleindex baa00cf72d..fde0b877f6 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -179,15 +179,18 @@ LANGFUSE_AWS_BEDROCK_REGION="eu-west-1"LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-haiku-4-5-20251001-v1:0"LANGFUSE_IN_APP_AGENT_AWS_PROFILE="playground"+# V4 migration flags.+# Write target: `legacy` | `dual` | `events_only`.+LANGFUSE_MIGRATION_V4_WRITE_MODE=dual+# Gate the V4 events_full read paths (UI, tRPC, v2 APIs, observations API).+# Self-hosted `dual` deployments must set this to `true` to offer users the V4+# preview toggle; with `dual` + `false` the preview stays unavailable to users.+LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true+# OTel ingestion behaviour: `dual_write` (SDK-version dispatch) or `direct`.+LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write+# Legacy tracing UI controlsLANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH=false-# Events table migration-LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS=true-LANGFUSE_ENABLE_EVENTS_TABLE_UI=true-LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS=true-LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS=true-LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE=true-CLICKHOUSE_USE_LIGHTWEIGHT_UPDATE="true"CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION=truediff --git a/.gitignore b/.gitignoreindex 5a148e0e32..512b4e1c44 100644--- a/.gitignore+++ b/.gitignore@@ -26,6 +26,9 @@ next-env.d.ts# production/build+# claude worktrees+.claude/worktrees+# idea.ideadiff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex 59dd0a443f..928ce03a30 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -11,6 +11,23 @@# - pnpm run dx# - pnpm run dx-f# - pnpm run ch:reset+#+# Self-hosted v4 rollout note:+# The events_full / events_core / events_core_mv / observations_batch_staging+# definitions below are intentionally NOT promoted to production CH migrations+# yet. They depend on ClickHouse features that are only available on recent+# versions:+# * `enable_block_number_column` / `enable_block_offset_column` table SETTINGS require ClickHouse >= 24.5.+# * `text` indexes and `enable_full_text_index` require ClickHouse >= 25.x.+# Self-hosters on older versions would be blocked from adopting v4 if we+# shipped these inline as migrations. Once v4 becomes the mainline and we can+# assume a 25.12+ minimum, these definitions will be promoted to proper+# migrations. Until then, this script is the documented way to roll out the+# v4 events pipeline tables.++# When making changes below, treat them like migrations, i.e. DO NOT modify the column inline.+# Instead add a table mutation adding a net new column.+# Also, populate the migrations in https://docs.google.com/document/d/1bvz3FUFn3T4rfJ_U1qIh36FcJGfUVQwdAIOAHa3wPnA.# Load environment variables[ -f ../../.env ] && source ../../.env@@ -72,12 +89,17 @@ clickhouse client \--database="${CLICKHOUSE_DB}" \--multiquery <<EOF--- Create observations_batch_staging table for batch processing--- This table uses 3-minute partitions to efficiently process observations in batches--- and merge them with traces data into the events table.--- Partitions are automatically expired after 12 hours via TTL (ttl_only_drop_parts=1--- ensures only complete partitions are dropped, not individual rows).--- See LFE-7122 for implementation details.+-- Staging table for the dual-write pipeline that populates events_full.+-- Ingestion writes every observation (and trace-as-synthetic-observation) here+-- with an s3_first_seen_timestamp; the periodic event-propagation job in the+-- worker reads completed 3-minute partitions, joins them with `traces`, and+-- inserts the result into `events_full`.+--+-- Partitions are automatically expired after 48 hours via TTL. The 48h window+-- (vs. the 12h used internally for Langfuse Cloud) gives self-hosters a+-- multi-day grace period to recover the propagation job after an incident+-- without losing staging data. `ttl_only_drop_parts = 1` ensures only complete+-- partitions are dropped, never individual rows.CREATE TABLE IF NOT EXISTS observations_batch_staging(id String,@@ -116,8 +138,9 @@ CREATE TABLE IF NOT EXISTS observations_batch_stagingevent_ts DateTime64(3),is_deleted UInt8,s3_first_seen_timestamp DateTime64(3),- environment LowCardinality(String) DEFAULT 'default',-) ENGINE = ReplacingMergeTree(event_ts, is_deleted)+ environment LowCardinality(String) DEFAULT 'default'+)+ENGINE = ReplacingMergeTree(event_ts, is_deleted)PARTITION BY toStartOfInterval(s3_first_seen_timestamp, INTERVAL 3 MINUTE)PRIMARY KEY (project_id, toDate(s3_first_seen_timestamp))ORDER BY (@@ -126,162 +149,140 @@ ORDER BY (trace_id,id)-TTL s3_first_seen_timestamp + INTERVAL 12 HOUR+TTL s3_first_seen_timestamp + INTERVAL 48 HOURSETTINGS ttl_only_drop_parts = 1;--- Create new events table for development setups.--- We expect this to be fully immutable and eventually replace observations.--- Remove IF NOT EXISTS when moving this to prod migrations.-SET enable_full_text_index=1;-+-- events_full is the immutable, full-fidelity event table that will eventually+-- replace observations. It is populated by the worker propagation job that+-- joins observations_batch_staging with traces and dataset_run_items.CREATE TABLE IF NOT EXISTS events_full- (- project_id String,- trace_id String,- span_id String,- parent_span_id String,-- start_time DateTime64(6),- end_time Nullable(DateTime64(6)),-- -- Core properties- name String,- type LowCardinality(String),- environment LowCardinality(String) DEFAULT 'default',- version String,- release String,- trace_name String,- user_id String,- session_id String,- tags Array(String),- level LowCardinality(String),- status_message String, -- Threat '' and null the same for search- completion_start_time Nullable(DateTime64(6)),- is_app_root Bool DEFAULT false,-- -- Updateable properties- bookmarked Bool DEFAULT false,- public Bool DEFAULT false,-- -- Prompt- prompt_id String,- prompt_name String,- prompt_version Nullable(UInt16),-- -- Model- model_id String,- provided_model_name String,- model_parameters String,-- -- Usage and Cost- provided_usage_details Map(LowCardinality(String), UInt64),- usage_details Map(LowCardinality(String), UInt64),- provided_cost_details Map(LowCardinality(String), Decimal(18,12)),- cost_details Map(LowCardinality(String), Decimal(18,12)),- calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),- calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),- calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),- total_cost Decimal(18, 12) ALIAS cost_details['total'],-- usage_pricing_tier_id Nullable(String),- usage_pricing_tier_name Nullable(String),-- -- Tools- tool_definitions Map(String, String),- tool_calls Array(String),- tool_call_names Array(String),-- -- I/O- input String CODEC(ZSTD(3)),- input_length UInt64 MATERIALIZED lengthUTF8(input),- output String CODEC(ZSTD(3)),- output_length UInt64 MATERIALIZED lengthUTF8(output),-- -- Metadata- metadata_names Array(String),- metadata_values Array(String),-- -- 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_version Nullable(DateTime64(6)),- 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,- service_version String,- scope_name String,- scope_version String,- telemetry_sdk_language LowCardinality(String),- telemetry_sdk_name String,- telemetry_sdk_version String,-- -- Generic props- blob_storage_file_path String,- event_bytes UInt64,- created_at DateTime64(6) DEFAULT now(),- updated_at DateTime64(6) DEFAULT now(),- event_ts DateTime64(6),- is_deleted UInt8,-- -- Indexes- INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,- INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,- INDEX idx_fts_input_low lower(input) TYPE text(- tokenizer = splitByNonAlpha- ),- INDEX idx_fts_output_low lower(output) TYPE text(- tokenizer = splitByNonAlpha- ),- INDEX idx_fts_metadata_values metadata_values TYPE text(- tokenizer = splitByNonAlpha- ),- INDEX idx_fts_metadata_names metadata_names TYPE text(- tokenizer = splitByNonAlpha- ),-- -- Full Text Search Indexes (We should try different index sizes, e.g. 2048, 4096, or 8192)- -- Add after backfill as they limit backfill throughput performance- -- INDEX idx_fts_input_1 input TYPE ngrambf_v1(1, 1024, 1, 0) GRANULARITY 1,- -- INDEX idx_fts_input_2 input TYPE ngrambf_v1(2, 1024, 1, 0) GRANULARITY 1,- -- INDEX idx_fts_input_4 input TYPE ngrambf_v1(4, 1024, 1, 0) GRANULARITY 1,- -- INDEX idx_fts_input_8 input TYPE ngrambf_v1(8, 1024, 1, 0) GRANULARITY 1,-- -- INDEX idx_fts_output_1 output TYPE ngrambf_v1(1, 1024, 1, 0) GRANULARITY 1,- -- INDEX idx_fts_output_2 output TYPE ngrambf_v1(2, 1024, 1, 0) GRANULARITY 1,- -- INDEX idx_fts_output_4 output TYPE ngrambf_v1(4, 1024, 1, 0) GRANULARITY 1,- -- INDEX idx_fts_output_8 output TYPE ngrambf_v1(8, 1024, 1, 0) GRANULARITY 1,- )- ENGINE = ReplacingMergeTree(event_ts, is_deleted)- -- ENGINE = (Replicated)ReplacingMergeTree(event_ts, is_deleted)- PARTITION BY toYYYYMM(start_time)- PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))- ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)- SAMPLE BY xxHash32(trace_id)- SETTINGS- index_granularity_bytes = '64Mi', -- Default 10MiB. Avoid small granules due to large rows.+(+ project_id String,+ trace_id String,+ span_id String,+ parent_span_id String,++ start_time DateTime64(6),+ end_time Nullable(DateTime64(6)),++ -- Core properties+ name String,+ type LowCardinality(String),+ environment LowCardinality(String) DEFAULT 'default',+ version String,+ release String,+ trace_name String,+ user_id String,+ session_id String,+ tags Array(String),+ level LowCardinality(String),+ status_message String,+ completion_start_time Nullable(DateTime64(6)),+ is_app_root Bool DEFAULT false,++ -- Updateable properties+ bookmarked Bool DEFAULT false,+ public Bool DEFAULT false,++ -- Prompt+ prompt_id String,+ prompt_name String,+ prompt_version Nullable(UInt16),++ -- Model+ model_id String,+ provided_model_name String,+ model_parameters String,++ -- Usage and Cost+ provided_usage_details Map(LowCardinality(String), UInt64),+ usage_details Map(LowCardinality(String), UInt64),+ provided_cost_details Map(LowCardinality(String), Decimal(18,12)),+ cost_details Map(LowCardinality(String), Decimal(18,12)),+ calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),+ calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ total_cost Decimal(18, 12) ALIAS cost_details['total'],++ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),++ -- Tools+ tool_definitions Map(String, String),+ tool_calls Array(String),+ tool_call_names Array(String),++ -- I/O+ input String CODEC(ZSTD(3)),+ input_length UInt64 MATERIALIZED lengthUTF8(input),+ output String CODEC(ZSTD(3)),+ output_length UInt64 MATERIALIZED lengthUTF8(output),++ -- Metadata+ metadata_names Array(String),+ metadata_values Array(String),++ -- Experiment properties+ experiment_id String,+ experiment_name String,+ experiment_metadata_names Array(String),+ experiment_metadata_values Array(String),+ experiment_description String,+ experiment_dataset_id String,+ experiment_item_id String,+ experiment_item_version Nullable(DateTime64(6)),+ experiment_item_expected_output String,+ experiment_item_metadata_names Array(String),+ experiment_item_metadata_values Array(String),+ experiment_item_root_span_id String,++ -- Source metadata (Instrumentation)+ source LowCardinality(String),+ service_name String,+ service_version String,+ scope_name String,+ scope_version String,+ telemetry_sdk_language LowCardinality(String),+ telemetry_sdk_name String,+ telemetry_sdk_version String,++ -- Generic props+ blob_storage_file_path String,+ event_bytes UInt64,+ created_at DateTime64(6) DEFAULT now(),+ updated_at DateTime64(6) DEFAULT now(),+ event_ts DateTime64(6),+ is_deleted UInt8,++ -- Indexes+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,+ INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,+ INDEX idx_fts_input_low lower(input) TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_output_low lower(output) TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha)+)+ENGINE = ReplacingMergeTree(event_ts, is_deleted)+PARTITION BY toYYYYMM(start_time)+PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))+ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)+SAMPLE BY xxHash32(trace_id)+SETTINGS+ index_granularity_bytes = '64Mi', -- Default 10MiB. Prevents very small granules due to large rows.merge_max_block_size_bytes = '64Mi',enable_block_number_column = 1,enable_block_offset_column = 1,prewarm_mark_cache = 1,- prewarm_primary_key_cache = 1- ;+ prewarm_primary_key_cache = 1,+ enable_full_text_index = 1;--- Create events_core table - lightweight version with truncated input/output/metadata for fast queries--- This table is populated via materialized view from the events_full table.+-- events_core is the lightweight, query-optimized projection of events_full+-- with truncated input/output/metadata. It is populated via the events_core_mv+-- materialized view defined below.CREATE TABLE IF NOT EXISTS events_core(project_id String,@@ -391,12 +392,8 @@ CREATE TABLE IF NOT EXISTS events_coreINDEX idx_provided_model_name provided_model_name TYPE bloom_filter(0.01) GRANULARITY 2,INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,INDEX idx_metadata_names metadata_names TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_fts_metadata_values metadata_values TYPE text(- tokenizer = splitByNonAlpha- ),- INDEX idx_fts_metadata_names metadata_names TYPE text(- tokenizer = splitByNonAlpha- )+ INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha))ENGINE = ReplacingMergeTree(event_ts, is_deleted)PARTITION BY toYYYYMM(start_time)@@ -407,10 +404,11 @@ SETTINGSenable_block_number_column = 1,enable_block_offset_column = 1,prewarm_mark_cache = 1,- prewarm_primary_key_cache = 1;- -- cache_populated_by_fetch = 1; -- Not available in OSS ClickHouse+ prewarm_primary_key_cache = 1,+ enable_full_text_index = 1;+ -- cache_populated_by_fetch = 1; -- Not available in OSS ClickHouse--- Materialized view to populate events_core from events_full table+-- Materialized view to populate events_core from events_full.CREATE MATERIALIZED VIEW IF NOT EXISTS events_core_mv TO events_core ASSELECTproject_id,diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex d34965c60f..b69951dfd1 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -81,6 +81,7 @@ const EnvSchema = z.object({CLICKHOUSE_URL: z.url(),CLICKHOUSE_READ_ONLY_URL: z.url().optional(),CLICKHOUSE_EVENTS_READ_ONLY_URL: z.url().optional(),+ CLICKHOUSE_CLUSTER_ENABLED: z.enum(["true", "false"]).default("true"),CLICKHOUSE_CLUSTER_NAME: z.string().default("default"),CLICKHOUSE_DB: z.string().default("default"),CLICKHOUSE_USER: z.string(),@@ -261,6 +262,14 @@ const EnvSchema = z.object({.enum(["true", "false"]).default("true"),+ // V4 write mode. Mirrors worker/src/env.ts so the web package can gate+ // public API routes that rely on the legacy traces/observations tables.+ // The worker owns the writes; the web only needs to know whether legacy+ // tables are still being populated to decide whether to serve reads.+ LANGFUSE_MIGRATION_V4_WRITE_MODE: z+ .enum(["legacy", "dual", "events_only"])+ .default("legacy"),+LANGFUSE_S3_LIST_MAX_KEYS: z.coerce.number().positive().default(200),LANGFUSE_S3_RATE_ERROR_SLOWDOWN_ENABLED: z.enum(["true", "false"])diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.tsindex 1a97e24a6f..e7456758ff 100644--- a/packages/shared/src/server/clickhouse/client.ts+++ b/packages/shared/src/server/clickhouse/client.ts@@ -25,6 +25,7 @@ const EVENTS_TABLE_READ_PATH_ENV_KEYS = ["LANGFUSE_ENABLE_EVENTS_TABLE_UI","LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS","LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS",+ "LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN",] as const;/**diff --git a/packages/shared/src/server/clickhouse/queryTracking.ts b/packages/shared/src/server/clickhouse/queryTracking.tsindex 4e2a4d1872..8a5fcb4269 100644--- a/packages/shared/src/server/clickhouse/queryTracking.ts+++ b/packages/shared/src/server/clickhouse/queryTracking.ts@@ -1,3 +1,4 @@+import { env } from "../../env";import { queryClickhouse } from "../repositories";// ============================================================================@@ -14,6 +15,20 @@ export function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+/**+ * Builds a system-table reference, optionally wrapped in clusterAllReplicas+ * when CH is deployed as a cluster. Single-node deployments (self-hosted) read+ * the local table directly.+ */+function systemTableRef(+ table: "system.processes" | "system.query_log",+): string {+ if (env.CLICKHOUSE_CLUSTER_ENABLED === "true") {+ return `clusterAllReplicas('${env.CLICKHOUSE_CLUSTER_NAME}', '${table}')`;+ }+ return table;+}+// ============================================================================// Query Status Polling// ============================================================================@@ -35,7 +50,7 @@ export async function pollQueryStatus(const running = await queryClickhouse<{ query_id: string }>({query: `SELECT query_id- FROM clusterAllReplicas('default', 'system.processes')+ FROM ${systemTableRef("system.processes")}WHERE query_id = {queryId: String}LIMIT 1`,@@ -59,7 +74,7 @@ export async function pollQueryStatus(}>({query: `SELECT type, exception_code- FROM clusterAllReplicas('default', 'system.query_log')+ FROM ${systemTableRef("system.query_log")}WHERE query_id = {queryId: String}ORDER BY event_time_microseconds DESCLIMIT 1@@ -107,7 +122,7 @@ export async function getQueryError(const result = await queryClickhouse<{ exception_message: string }>({query: `SELECT exception as exception_message- FROM clusterAllReplicas('default', 'system.query_log')+ FROM ${systemTableRef("system.query_log")}WHERE query_id = {queryId: String}AND type != 'QueryStart'AND exception != ''diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex f929416bbb..2b7a4ca367 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -22,6 +22,10 @@ import {convertClickhouseToDomain,convertClickhouseTracesListToDomain,} from "./traces_converters";+import {+ getTraceByIdFromTracesTable,+ getTracesIdentifierForSessionFromTracesTable,+} from "./traces";import {DateTimeFilter,type Filter,@@ -82,6 +86,7 @@ import {} from "./definitions";import type { AnalyticsObservationEvent } from "../analytics-integrations/types";import {+ getObservationByIdFromObservationsTable,ObservationsTableQueryResult,ObservationTableQuery,} from "./observations";@@ -943,6 +948,9 @@ async function getObservationByIdFromEventsTableInternal({/*** Get a trace by ID from the events table.* Compatible with getTraceById but queries the events table instead.+ *+ * Avoid using the `excludeInputOutput` and `excludeMetadata` fields as they+ * are only for backwards compatibility with the existing `getTraceById` interface.*/export const getTraceByIdFromEventsTable = async ({traceId,@@ -952,6 +960,8 @@ export const getTraceByIdFromEventsTable = async ({renderingProps = DEFAULT_RENDERING_PROPS,clickhouseFeatureTag = "tracing",preferredClickhouseService,+ excludeInputOutput = false,+ excludeMetadata = false,}: {traceId: string;projectId: string;@@ -960,6 +970,10 @@ export const getTraceByIdFromEventsTable = async ({renderingProps?: RenderingProps;clickhouseFeatureTag?: string;preferredClickhouseService?: PreferredClickhouseService;+ /** When true, sets input/output columns to empty in the query to reduce database load */+ excludeInputOutput?: boolean;+ /** When true, sets metadata column to empty in the query to reduce database load */+ excludeMetadata?: boolean;}) => {// Build traces CTE using eventsTracesAggregation// Pass truncated flag to select events_core (truncated) or events_full (full I/O)@@ -980,7 +994,6 @@ export const getTraceByIdFromEventsTable = async ({"t.id","t.name","t.user_id",- "t.metadata","t.release","t.version","t.project_id",@@ -993,6 +1006,7 @@ export const getTraceByIdFromEventsTable = async ({"t.created_at","t.updated_at",)+ .select(excludeMetadata ? "map() as metadata" : "t.metadata").select("0 as is_deleted");if (timestamp) {@@ -1006,7 +1020,9 @@ export const getTraceByIdFromEventsTable = async ({// Handle input/output with truncation// Note: eventsTracesAggregation above is responsible for choosing events_core/events_full- if (renderingProps.truncated) {+ if (excludeInputOutput) {+ queryBuilder.select("'' as input").select("'' as output");+ } else if (renderingProps.truncated) {queryBuilder.select(`leftUTF8(t.input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input`,@@ -1063,6 +1079,64 @@ export const getTraceByIdFromEventsTable = async ({return res.shift();};+/**+ * Routing wrapper for "trace by id" reads.+ *+ * If data is only written into the events tables, we look there and go to+ * traces otherwise.+ *+ * @deprecated Please prefer `getTraceByIdFromEventsTable` for new use-cases.+ * This should be exclusively used for backwards compatibility if the write mode+ * is events_only.+ */+export const getTraceById = async (+ params: Parameters<typeof getTraceByIdFromTracesTable>[0],+) => {+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {+ return getTraceByIdFromTracesTable(params);+ }+ return getTraceByIdFromEventsTable(params);+};++/**+ * Routing wrapper for "observation by id" reads.+ *+ * If data is only written into the events tables, we look there and go to the+ * legacy observations table otherwise.+ *+ * @deprecated Please prefer `getObservationByIdFromEventsTable` for new+ * use-cases. This should be exclusively used for backwards compatibility if the+ * write mode is events_only.+ */+export const getObservationById = async (+ params: Parameters<typeof getObservationByIdFromObservationsTable>[0],+) => {+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {+ return getObservationByIdFromObservationsTable(params);+ }+ return getObservationByIdFromEventsTable(params);+};++/**+ * Routing wrapper for "trace identifiers for session" reads.+ *+ * If data is only written into the events tables, we look there and go to the+ * legacy traces table otherwise.+ *+ * @deprecated Please prefer `getTracesIdentifierForSessionFromEvents` for new+ * use-cases. This should be exclusively used for backwards compatibility if the+ * write mode is events_only.+ */+export const getTracesIdentifierForSession = async (+ projectId: string,+ sessionId: string,+) => {+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {+ return getTracesIdentifierForSessionFromTracesTable(projectId, sessionId);+ }+ return getTracesIdentifierForSessionFromEvents(projectId, sessionId);+};+type PublicApiObservationsQuery = {projectId: string;page: number;diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 199211ff6d..19bfc51580 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -328,7 +328,15 @@ export const getObservationForTraceIdByName = async ({return records.map((record) => convertObservation(record));};-export const getObservationById = async ({+/**+ * Retrieves an observation by its ID from the legacy `observations` table.+ *+ * Prefer the routing wrapper `getObservationById` (in repositories/events.ts)+ * for application reads: it dispatches between this legacy reader and the events+ * table based on the V4 migration flags. Call this directly only when you+ * specifically need the legacy table (e.g. backfills, migration tooling).+ */+export const getObservationByIdFromObservationsTable = async ({id,projectId,fetchWithInputOutput = false,diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 52ed286b1b..5719ef7b35 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -498,13 +498,15 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({};/**- * Retrieves a trace record by its ID and associated project ID, with optional filtering by timestamp range.- * If no timestamp filters are provided, runs two queries in parallel:- * 1. One with a 7-day fromTimestamp filter (typically faster)- * 2. One without any timestamp filters (complete but slower)- * Returns the first non-empty result.+ * Retrieves a trace record by its ID and associated project ID from the legacy+ * `traces` table.+ *+ * Prefer the routing wrapper `getTraceById` (in repositories/events.ts) for+ * application reads: it dispatches between this legacy reader and the events+ * table based on the V4 migration flags. Call this directly only when you+ * specifically need the legacy table (e.g. backfills, migration tooling).*/-export const getTraceById = async ({+export const getTraceByIdFromTracesTable = async ({traceId,projectId,timestamp,@@ -884,7 +886,17 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {});};-export const getTracesIdentifierForSession = async (+/**+ * Retrieves identifier rows for the traces referencing a session from the+ * legacy `traces` table.+ *+ * Prefer the routing wrapper `getTracesIdentifierForSession` (in+ * repositories/events.ts) for application reads: it dispatches between this+ * legacy reader and the events table based on the V4 migration flags. Call this+ * directly only when you specifically need the legacy table (e.g. backfills,+ * migration tooling).+ */+export const getTracesIdentifierForSessionFromTracesTable = async (projectId: string,sessionId: string,) => {diff --git a/turbo.json b/turbo.jsonindex f746df4dd5..72a5a30d45 100644--- a/turbo.json+++ b/turbo.json@@ -69,7 +69,7 @@"outputLogs": "errors-only"},"lint": {- "dependsOn": ["@repo/eslint-plugin#build"],+ "dependsOn": ["@repo/eslint-plugin#build", "^build"],"cache": true,"outputLogs": "errors-only","outputs": []diff --git a/web/eslint.config.mjs b/web/eslint.config.mjsindex f3113c3d52..5ac2574f67 100644--- a/web/eslint.config.mjs+++ b/web/eslint.config.mjs@@ -6,6 +6,16 @@ export default [...nextConfig,...storybook.configs["flat/recommended"],+ // Tests legitimately exercise backwards-compatible (deprecated) read paths+ // such as getTraceById/getObservationById, so allow them in test code.+ {+ name: "langfuse/web/tests-allow-deprecated",+ files: ["src/__tests__/**", "src/__e2e__/**", "**/*.servertest.ts"],+ rules: {+ "@typescript-eslint/no-deprecated": "off",+ },+ },+// Restrict react-icons imports{name: "langfuse/web/react-icons-restriction",diff --git a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts b/web/src/__tests__/server/clickhouseSearchCondition.servertest.tsindex fcfa9a081f..2109cc1f24 100644--- a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts+++ b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts@@ -10,7 +10,7 @@ import {import { randomUUID } from "crypto";const maybeEventsTable =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.tsindex 8dfe35888b..d253817421 100644--- a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts+++ b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts@@ -43,7 +43,9 @@ import { EvalTargetObject } from "@langfuse/shared";const orgIds: string[] = [];const maybe =- env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS === "true" ? describe : describe.skip;+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"+ ? describe+ : describe.skip;async function prepare() {const { project, org } = await createOrgProjectAndApiKey();@@ -264,13 +266,13 @@ maybe("evals.testRunCodeEval", () => {]);const mutableEnv = env as unknown as {- LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS: "true" | "false";+ LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN: "true" | "false";};const originalEventsTableFlagsFlag =- mutableEnv.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS;+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN;try {- mutableEnv.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS = "false";+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "false";const response = await caller.evals.testRunCodeEval({projectId: project.id,@@ -314,7 +316,7 @@ maybe("evals.testRunCodeEval", () => {executionTraceFromTimestamp: expect.any(Date),});} finally {- mutableEnv.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS =+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN =originalEventsTableFlagsFlag;}});diff --git a/web/src/__tests__/server/comments-api.servertest.ts b/web/src/__tests__/server/comments-api.servertest.tsindex 3a229adda1..a97e1e6392 100644--- a/web/src/__tests__/server/comments-api.servertest.ts+++ b/web/src/__tests__/server/comments-api.servertest.ts@@ -59,6 +59,7 @@ describe("Create and get comments", () => {});it("should fail to create comment if reference object does not exist", async () => {+ expect.assertions(2); // Ensure that we confirm two thingstry {await makeZodVerifiedAPICall(z.object({@@ -75,8 +76,11 @@ describe("Create and get comments", () => {},);} catch (error) {- expect((error as Error).message).toBe(- `API call did not return 200, returned status 404, body {\"message\":\"Reference object, TRACE: invalid-trace-id not found in Clickhouse. Skipping creating comment.\",\"error\":\"LangfuseNotFoundError\"}`,+ expect((error as Error).message).toContain(+ `API call did not return 200, returned status 404`,+ );+ expect((error as Error).message).toContain(+ `TRACE: invalid-trace-id not found`,);}});diff --git a/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.tsindex 0bd4e1b36e..ab1d7cc503 100644--- a/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts+++ b/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts@@ -28,7 +28,7 @@ import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";// Skip when events table is not enabled (v2 queries require events_core).const maybe =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;@@ -207,7 +207,7 @@ async function seedFromSeeder(targetProjectId: string) {const maxTs = new Date(maxTsResult[0]?.max_ts ?? Date.now());let maxTsEvents = new Date(0);- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {const maxTsEventsResult = await queryClickhouse<{ max_ts: string }>({query: `SELECT max(event_ts) as max_ts FROM events_core WHERE project_id = {projectId: String}`,params: { projectId: targetProjectId },@@ -441,7 +441,7 @@ describe("dashboard v1 vs v2 consistency", () => {let toTimestamp: string;beforeAll(async () => {- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS !== "true") return;+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") return;const org = await createOrgProjectAndApiKey();projectId = org.projectId;diff --git a/web/src/__tests__/server/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.tsindex a7a6a2d195..2751d0c0ca 100644--- a/web/src/__tests__/server/evals-trpc.servertest.ts+++ b/web/src/__tests__/server/evals-trpc.servertest.ts@@ -3,7 +3,7 @@ import type * as SharedEnvModule from "@langfuse/shared/src/env";const { runCodeEvalTestForJobConfigMock } = vi.hoisted(() => {process.env.LANGFUSE_CODE_EVAL_DISPATCHER = "insecure-local";- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_UI = "true";+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";return {runCodeEvalTestForJobConfigMock: vi.fn(),diff --git a/web/src/__tests__/server/fts-rewrites.servertest.ts b/web/src/__tests__/server/fts-rewrites.servertest.tsindex 40c5dc9e68..b68a9c3c9c 100644--- a/web/src/__tests__/server/fts-rewrites.servertest.ts+++ b/web/src/__tests__/server/fts-rewrites.servertest.ts@@ -10,7 +10,7 @@ import {} from "@langfuse/shared/src/server";const maybeEventsTable =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tsindex 8b6683fae4..89c8bdd072 100644--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts@@ -127,11 +127,11 @@ import {} from "@/src/features/mcp/features/datasets/schema";const maybeEventsTable =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;const maybeEventsTableIt =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true" ? it : it.skip;+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true" ? it : it.skip;const createObservationEvent = (params: {projectId: string;diff --git a/web/src/__tests__/server/metrics-v2-api.servertest.ts b/web/src/__tests__/server/metrics-v2-api.servertest.tsindex e036048e8d..2e539abc64 100644--- a/web/src/__tests__/server/metrics-v2-api.servertest.ts+++ b/web/src/__tests__/server/metrics-v2-api.servertest.ts@@ -14,7 +14,7 @@ import {import { env } from "@/src/env.mjs";import waitForExpect from "wait-for-expect";-const hasV2Apis = env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true";+const hasV2Apis = env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";const maybe = hasV2Apis ? describe : describe.skip;describe("/api/public/v2/metrics API Endpoint", () => {diff --git a/web/src/__tests__/server/observation-api.servertest.ts b/web/src/__tests__/server/observation-api.servertest.tsindex 015295da46..313c79e259 100644--- a/web/src/__tests__/server/observation-api.servertest.ts+++ b/web/src/__tests__/server/observation-api.servertest.ts@@ -471,7 +471,7 @@ describe("/api/public/observations API Endpoint", () => {};// Run tests with both implementations- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {runTestSuite(true); // with events table}runTestSuite(false); // with observations tablediff --git a/web/src/__tests__/server/observations-api-v2.servertest.ts b/web/src/__tests__/server/observations-api-v2.servertest.tsindex f7672757e4..04757be0b7 100644--- a/web/src/__tests__/server/observations-api-v2.servertest.ts+++ b/web/src/__tests__/server/observations-api-v2.servertest.ts@@ -28,7 +28,7 @@ const getObservations = (url: string) =>const getRaw = (url: string) => makeAPICall("GET", url, undefined, auth);const maybe =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/web/src/__tests__/server/observations-api.servertest.ts b/web/src/__tests__/server/observations-api.servertest.tsindex a878d0ea41..5ece0ee0a0 100644--- a/web/src/__tests__/server/observations-api.servertest.ts+++ b/web/src/__tests__/server/observations-api.servertest.ts@@ -573,7 +573,7 @@ describe("/api/public/observations API Endpoint", () => {};// Run tests with both implementations- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {runTestSuite(true); // with events table}runTestSuite(false); // with observations table@@ -917,7 +917,7 @@ describe("/api/public/observations API Endpoint", () => {};// Run all advanced filtering tests for both implementations- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {runAdvancedFilterTestSuite(true); // with events table}runAdvancedFilterTestSuite(false); // with observations table@@ -1259,7 +1259,7 @@ describe("/api/public/observations API Endpoint", () => {};// Run parentObservationId filter tests for both implementations- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {runParentObservationIdFilterTestSuite(true); // with events table}runParentObservationIdFilterTestSuite(false); // with observations tablediff --git a/web/src/__tests__/server/queryBuilder.servertest.ts b/web/src/__tests__/server/queryBuilder.servertest.tsindex ebff56477b..756b98feea 100644--- a/web/src/__tests__/server/queryBuilder.servertest.ts+++ b/web/src/__tests__/server/queryBuilder.servertest.ts@@ -3773,7 +3773,7 @@ describe("queryBuilder", () => {describe("pairExpand map expansion (v2)", () => {const isEventsTableV2Enabled =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true" ? it : it.skip;+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true" ? it : it.skip;let hasLegacyEventsTable = false;const maybeItWithEventsTable = (@@ -3787,7 +3787,7 @@ describe("queryBuilder", () => {};beforeAll(async () => {- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS !== "true") return;+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") return;try {const result = await clickhouseClient().query({@@ -4749,11 +4749,11 @@ describe("query builder measure-aggregation validation", () => {describe("events_traces traceName filter", () => {const isEventsTableV2Enabled =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true" ? it : it.skip;+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true" ? it : it.skip;let hasLegacyEventsTable = false;beforeAll(async () => {- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS !== "true") return;+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") return;try {const result = await clickhouseClient().query({diff --git a/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.ts b/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.tsindex 8195e82fbd..15ef538cdc 100644--- a/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.ts+++ b/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.ts@@ -4,7 +4,7 @@ import { env } from "@/src/env.mjs";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const isEventsTableV2Enabled =- env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true" ? it : it.skip;+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true" ? it : it.skip;let hasLegacyEventsTable = false;const maybeIt = (name: string, testFn: () => Promise<void>): void => {diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tsindex 9c051a11ef..5c16443879 100644--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts@@ -22,7 +22,7 @@ import waitForExpect from "wait-for-expect";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const maybe =- env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts b/web/src/__tests__/server/repositories/experiment-items-repository.servertest.tsindex 9dc3d73fc4..3dd958b90e 100644--- a/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts@@ -81,7 +81,7 @@ function createRootObservationScore(params: {const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const maybe =- env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts b/web/src/__tests__/server/repositories/experiment-repository.servertest.tsindex 281d84a54f..f0725ecad3 100644--- a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/experiment-repository.servertest.ts@@ -16,7 +16,7 @@ import {const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const maybe =- env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/web/src/__tests__/server/scores-trpc-events-only.servertest.ts b/web/src/__tests__/server/scores-trpc-events-only.servertest.tsnew file mode 100644index 0000000000..ecd5a20078--- /dev/null+++ b/web/src/__tests__/server/scores-trpc-events-only.servertest.ts@@ -0,0 +1,214 @@+/**+ * Annotation-score session targeting for the events_only write mode.+ *+ * In events_only mode ingestion no longer writes into the legacy `traces`+ * table, so the session-existence check in `scores.createAnnotationScore` /+ * `scores.updateAnnotationScore` must read trace identifiers from the events+ * store. Both handlers call `getTracesIdentifierForSession`, which is a routing+ * wrapper (repositories/events.ts) that dispatches to the events table in+ * events_only mode and to the legacy traces table otherwise. Before the wrapper+ * existed the read hit the (empty) `traces` table and every session-targeted+ * annotation score create/update threw a misleading 404.+ *+ * The write mode is read from the parsed shared env at module load, so we force+ * it via process.env BEFORE any module is imported (mirrors+ * sessions-trpc-events-only.servertest.ts).+ */+import { vi } from "vitest";++// The events_full table is created only by the ClickHouse dev-tables setup,+// which runs in the default deploy-mode where .env.dev.example enables the v4+// preview opt-in. The -azure and -redis-cluster CI runs skip that setup, so the+// events table is absent. Capture the ORIGINAL opt-in flag BEFORE forcing it on+// so we can detect (and skip) those events-table-less environments.+const eventsTableAvailable = vi.hoisted(() => {+ const enabled =+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ // events_only requires the preview opt-in (web/worker env validation enforces+ // the pairing and web read paths gate on it).+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";+ return enabled;+});++import type { Session } from "next-auth";+import { ScoreConfigDataType } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ createEvent,+ createEventsCh,+ getTracesIdentifierForSessionFromEvents,+} from "@langfuse/shared/src/server";+import { env } from "@langfuse/shared/src/env";+import waitForExpect from "wait-for-expect";+import { randomUUID } from "crypto";++// Skip on environments without the events_full dev table (azure / redis-cluster+// CI). Mirrors the gating used across the other events-table server tests.+const maybe = eventsTableAvailable ? describe : describe.skip;++// At least one always-running test so the file does not hang on the redis+// connections opened by the tRPC caller imports when the events-table tests+// below are skipped via `maybe`.+describe("scores trpc (events_only write mode) liveness", () => {+ it("should not hang redis when the events table is unavailable", () => {});+});++maybe(+ "scores trpc annotation session targeting (events_only write mode)",+ () => {+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: "seed-org-id",+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ // Seed a single root event for a session into the events table and wait until+ // the session's traces are resolvable through the events-table reader the+ // annotation handlers route to in events_only mode.+ const seedSessionEvent = async (sessionId: string) => {+ const traceId = randomUUID();+ await createEventsCh([+ createEvent({+ id: traceId,+ span_id: traceId,+ trace_id: traceId,+ project_id: projectId,+ parent_span_id: "",+ type: "SPAN",+ session_id: sessionId,+ user_id: "user-a",+ start_time: Date.now() * 1000,+ }),+ ]);++ await waitForExpect(async () => {+ const traces = await getTracesIdentifierForSessionFromEvents(+ projectId,+ sessionId,+ );+ expect(traces.length).toBeGreaterThanOrEqual(1);+ });++ return traceId;+ };++ // Annotation create does not validate the config against Postgres, but update+ // does. Create one real config so both paths exercise the same input shape.+ const createConfig = async () => {+ const configId = randomUUID();+ await prisma.scoreConfig.create({+ data: {+ id: configId,+ projectId,+ name: `events-only-session-config-${configId.slice(0, 8)}`,+ dataType: ScoreConfigDataType.NUMERIC,+ },+ });+ return configId;+ };++ it("forces events_only write mode", () => {+ expect(env.LANGFUSE_MIGRATION_V4_WRITE_MODE).toBe("events_only");+ });++ it("createAnnotationScore resolves the session via the events table", async () => {+ const sessionId = randomUUID();+ await seedSessionEvent(sessionId);+ const configId = await createConfig();++ // Regression: before the routing wrapper this read the empty legacy `traces`+ // table and threw "No trace referencing session …".+ const score = await caller.scores.createAnnotationScore({+ projectId,+ name: "events-only-session-score",+ value: 1,+ stringValue: null,+ dataType: "NUMERIC",+ scoreTarget: { type: "session", sessionId },+ configId,+ environment: "default",+ });++ expect(score.sessionId).toBe(sessionId);+ expect(score.value).toBe(1);+ expect(score.source).toBe("ANNOTATION");+ });++ it("createAnnotationScore still 404s for a session with no events", async () => {+ const configId = await createConfig();++ await expect(+ caller.scores.createAnnotationScore({+ projectId,+ name: "events-only-missing-session-score",+ value: 1,+ stringValue: null,+ dataType: "NUMERIC",+ scoreTarget: { type: "session", sessionId: randomUUID() },+ configId,+ environment: "default",+ }),+ ).rejects.toThrow(/No trace referencing session/);+ });++ it("updateAnnotationScore upserts a session score via the events table", async () => {+ const sessionId = randomUUID();+ await seedSessionEvent(sessionId);+ const configId = await createConfig();++ // A score id that does not yet exist in ClickHouse, with a client-provided+ // timestamp, forces the upsert-along-ordering-key branch — the second caller+ // of getTracesIdentifierForSession.+ const score = await caller.scores.updateAnnotationScore({+ id: randomUUID(),+ projectId,+ name: "events-only-session-score",+ value: 2,+ stringValue: null,+ dataType: "NUMERIC",+ scoreTarget: { type: "session", sessionId },+ configId,+ timestamp: new Date(),+ environment: "default",+ });++ expect(score.sessionId).toBe(sessionId);+ expect(score.value).toBe(2);+ });+ },+);diff --git a/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts b/web/src/__tests__/server/sessions-trpc-events-only.servertest.tsnew file mode 100644index 0000000000..ca7d3b032e--- /dev/null+++ b/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts@@ -0,0 +1,204 @@+/**+ * Sparse trace_sessions behaviour for the events_only write mode.+ *+ * In events_only mode ingestion no longer upserts a trace_sessions row per+ * trace. trace_sessions becomes a sparse metadata side-table (rows only exist+ * once a session has been bookmarked or published). The reads must therefore:+ * - never 404 just because the Postgres row is missing (the session exists in+ * the events store) — covered by enforceSessionAccess + byIdWithScoresFromEvents,+ * - and bookmark/publish must upsert (create-on-demand) rather than update.+ *+ * The write mode is read from the parsed shared env at module load, so we force+ * it via process.env BEFORE any module is imported (mirrors+ * traces-trpc-events-only.servertest.ts).+ */+import { vi } from "vitest";++// The events_full table is created only by the ClickHouse dev-tables setup,+// which runs in the default deploy-mode where .env.dev.example enables the v4+// preview opt-in. The -azure and -redis-cluster CI runs skip that setup, so the+// events table is absent. Capture the ORIGINAL opt-in flag BEFORE forcing it on+// so we can detect (and skip) those events-table-less environments.+const eventsTableAvailable = vi.hoisted(() => {+ const enabled =+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ // events_only requires the preview opt-in (web/worker env validation enforces+ // the pairing and web read paths gate on it).+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";+ return enabled;+});++import type { Session } from "next-auth";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ createEvent,+ createEventsCh,+ getSessionMetricsFromEvents,+} from "@langfuse/shared/src/server";+import { env } from "@langfuse/shared/src/env";+import waitForExpect from "wait-for-expect";+import { randomUUID } from "crypto";++// Skip on environments without the events_full dev table (azure / redis-cluster+// CI). Mirrors the gating used across the other events-table server tests.+const maybe = eventsTableAvailable ? describe : describe.skip;++// At least one always-running test so the file does not hang on the redis+// connections opened by the tRPC caller imports when the events-table tests+// below are skipped via `maybe`.+describe("sessions trpc (events_only write mode) liveness", () => {+ it("should not hang redis when the events table is unavailable", () => {});+});++maybe("sessions trpc (events_only write mode)", () => {+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: "seed-org-id",+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ // Seed a single root event for a session into the events table and wait until+ // the session is countable (ClickHouse insert visibility can lag).+ const seedSessionEvent = async (sessionId: string) => {+ const traceId = randomUUID();+ await createEventsCh([+ createEvent({+ id: traceId,+ span_id: traceId,+ trace_id: traceId,+ project_id: projectId,+ parent_span_id: "",+ type: "SPAN",+ session_id: sessionId,+ user_id: "user-a",+ start_time: Date.now() * 1000,+ }),+ ]);++ await waitForExpect(async () => {+ const rows = await getSessionMetricsFromEvents({+ projectId,+ sessionIds: [sessionId],+ });+ expect(rows[0]?.session_id).toBe(sessionId);+ });++ return traceId;+ };++ it("forces events_only write mode", () => {+ expect(env.LANGFUSE_MIGRATION_V4_WRITE_MODE).toBe("events_only");+ });++ it("returns a session that has no trace_sessions row", async () => {+ const sessionId = randomUUID();++ // Precondition: no Postgres metadata row exists for this session.+ const before = await prisma.traceSession.findFirst({+ where: { id: sessionId, projectId },+ });+ expect(before).toBeNull();++ await seedSessionEvent(sessionId);++ const result = await caller.sessions.byIdWithScoresFromEvents({+ projectId,+ sessionId,+ });++ expect(result.id).toBe(sessionId);+ expect(result.bookmarked).toBe(false);+ expect(result.public).toBe(false);+ expect(result.countTraces).toBeGreaterThanOrEqual(1);+ });++ it("bookmark creates the trace_sessions row on demand and round-trips", async () => {+ const sessionId = randomUUID();+ await seedSessionEvent(sessionId);++ const before = await prisma.traceSession.findFirst({+ where: { id: sessionId, projectId },+ });+ expect(before).toBeNull();++ const mutated = await caller.sessions.bookmark({+ projectId,+ sessionId,+ bookmarked: true,+ });+ expect(mutated.id).toBe(sessionId);+ expect(mutated.bookmarked).toBe(true);++ const created = await prisma.traceSession.findFirst({+ where: { id: sessionId, projectId },+ });+ expect(created?.bookmarked).toBe(true);++ const read = await caller.sessions.byIdWithScoresFromEvents({+ projectId,+ sessionId,+ });+ expect(read.bookmarked).toBe(true);+ expect(read.public).toBe(false);+ });++ it("publish creates the trace_sessions row on demand and round-trips", async () => {+ const sessionId = randomUUID();+ await seedSessionEvent(sessionId);++ const before = await prisma.traceSession.findFirst({+ where: { id: sessionId, projectId },+ });+ expect(before).toBeNull();++ const mutated = await caller.sessions.publish({+ projectId,+ sessionId,+ public: true,+ });+ expect(mutated.id).toBe(sessionId);+ expect(mutated.public).toBe(true);++ const read = await caller.sessions.byIdWithScoresFromEvents({+ projectId,+ sessionId,+ });+ expect(read.public).toBe(true);+ expect(read.bookmarked).toBe(false);+ });+});diff --git a/web/src/__tests__/server/sessions-ui-table.servertest.ts b/web/src/__tests__/server/sessions-ui-table.servertest.tsindex 64f4df298e..9d338e01ba 100644--- a/web/src/__tests__/server/sessions-ui-table.servertest.ts+++ b/web/src/__tests__/server/sessions-ui-table.servertest.ts@@ -21,7 +21,7 @@ import { createTrace } from "@langfuse/shared/src/server";import { type FilterState } from "@langfuse/shared";import { env } from "@/src/env.mjs";-const isEventsPath = env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true";+const isEventsPath = env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";// Pick the right listing function based on env flagconst sessionsTable = isEventsPathdiff --git a/web/src/__tests__/server/traces-api.servertest.ts b/web/src/__tests__/server/traces-api.servertest.tsindex 57ac8ed6a6..ec5ad54c5d 100644--- a/web/src/__tests__/server/traces-api.servertest.ts+++ b/web/src/__tests__/server/traces-api.servertest.ts@@ -2012,7 +2012,7 @@ describe("/api/public/traces API Endpoint", () => {// Run test suite twice - once for each implementationrunTestSuite(false); // old traces table- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {runTestSuite(true); // Events table}});@@ -2360,7 +2360,7 @@ describe("/api/public/traces API Endpoint", () => {// Run test suite twice - once for each implementationrunTestSuite(false); // Good old traces table- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {runTestSuite(true); // Events table}});@@ -2575,7 +2575,7 @@ describe("/api/public/traces API Endpoint", () => {// Run for both table implementationsrunFilterTests(false);- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {runFilterTests(true);}});diff --git a/web/src/__tests__/server/traces-trpc-events-only.servertest.ts b/web/src/__tests__/server/traces-trpc-events-only.servertest.tsnew file mode 100644index 0000000000..68c15e2d82--- /dev/null+++ b/web/src/__tests__/server/traces-trpc-events-only.servertest.ts@@ -0,0 +1,225 @@+/**+ * Events-only write-mode routing for traces.bookmark / traces.publish.+ *+ * getTraceById (repositories/events.ts) routes reads to the events table only+ * when LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only; in legacy/dual the legacy+ * `traces` table is still written and is the freshest source, so reads stay+ * there. That flag is read from the parsed env at module load, and under vitest+ * the wrapper's env instance is not the same object a test could mutate at+ * runtime — so we force the mode via process.env BEFORE any module is imported.+ *+ * This is split into its own file because the env is process-wide for the file;+ * the dual-mode flag tests live in traces-trpc.servertest.ts.+ */+import { vi } from "vitest";++// The events_full table is created only by the ClickHouse dev-tables setup+// (CI's "Setup Dev Tables" step), which runs in the default deploy-mode where+// .env.dev.example enables the v4 preview opt-in. The -azure and -redis-cluster+// CI runs skip that setup, so the events table is absent and the reads below+// would error. Capture the ORIGINAL opt-in flag here, BEFORE the override forces+// it on — once forced, the parsed shared env always reports "true" and we could+// never detect the events-table-less environments.+const eventsTableAvailable = vi.hoisted(() => {+ const enabled =+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ // events_only requires the preview opt-in (web read paths gate on it, and+ // worker/web env validation enforces the pairing).+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";+ return enabled;+});++import type { Session } from "next-auth";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ createEvent,+ createEventsCh,+ getTraceByIdFromEventsTable,+ getTraceByIdFromTracesTable,+} from "@langfuse/shared/src/server";+import { env } from "@langfuse/shared/src/env";+import waitForExpect from "wait-for-expect";+import { randomUUID } from "crypto";++// Skip on environments without the events_full dev table (azure / redis-cluster+// CI). Mirrors the gating used across the other events-table server tests.+const maybe = eventsTableAvailable ? describe : describe.skip;++// At least one always-running test so the file does not hang on the redis+// connections opened by the tRPC caller imports when the events-table tests+// below are skipped via `maybe`.+describe("traces trpc (events_only write mode) liveness", () => {+ it("should not hang redis when the events table is unavailable", () => {});+});++maybe("traces trpc (events_only write mode)", () => {+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: "seed-org-id",+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ // Sanity check that the forced write mode reached the parsed shared env that+ // getTraceById routes on. If this ever regresses, the assertions below would+ // silently fall back to reading the (empty) legacy table.+ it("forces events_only write mode", () => {+ expect(env.LANGFUSE_MIGRATION_V4_WRITE_MODE).toBe("events_only");+ });++ // A trace ingested after the legacy->events cutover lives ONLY in the events+ // table. In events_only mode getTraceById must route the mutation read to the+ // events table; otherwise the legacy `traces` read returns undefined and the+ // bookmark silently no-ops.+ it("should bookmark a trace that only exists in the events table", async () => {+ const traceId = randomUUID();++ // Trace is written to the events table only - NOT the legacy table.+ await createEventsCh([+ createEvent({+ id: traceId,+ span_id: traceId,+ trace_id: traceId,+ project_id: projectId,+ parent_span_id: null,+ bookmarked: false,+ }),+ ]);++ // Precondition: legacy `traces` has no row (events_only scenario).+ const legacyTrace = await getTraceByIdFromTracesTable({+ traceId,+ projectId,+ clickhouseFeatureTag: "tracing-test",+ });+ expect(legacyTrace).toBeUndefined();++ // Ensure the freshly-inserted event is queryable before mutating+ // (ClickHouse insert visibility can lag).+ await waitForExpect(async () => {+ const eventTrace = await getTraceByIdFromEventsTable({+ projectId,+ traceId,+ renderingProps: { truncated: false, shouldJsonParse: true },+ });+ expect(eventTrace?.id).toBe(traceId);+ });++ const result = await caller.traces.bookmark({+ projectId,+ traceId,+ bookmarked: true,+ });++ expect(result).toBeDefined();+ expect(result?.id).toEqual(traceId);+ expect(result?.bookmarked).toBe(true);++ await waitForExpect(async () => {+ const eventTraceFull = await getTraceByIdFromEventsTable({+ projectId,+ traceId,+ renderingProps: {+ truncated: false,+ shouldJsonParse: true,+ },+ });+ expect(eventTraceFull).toBeDefined();+ expect(eventTraceFull?.bookmarked).toBe(true);+ });+ });++ // Same routing as the bookmark case, but publish throws NOT_FOUND (rewrapped+ // as INTERNAL_SERVER_ERROR) instead of silently no-opping when the read is+ // misrouted to the empty legacy table.+ it("should make a trace public that only exists in the events table", async () => {+ const traceId = randomUUID();++ // Trace is written to the events table only - NOT the legacy table.+ await createEventsCh([+ createEvent({+ id: traceId,+ span_id: traceId,+ trace_id: traceId,+ project_id: projectId,+ parent_span_id: null,+ public: false,+ }),+ ]);++ // Precondition: legacy `traces` has no row (events_only scenario).+ const legacyTrace = await getTraceByIdFromTracesTable({+ traceId,+ projectId,+ clickhouseFeatureTag: "tracing-test",+ });+ expect(legacyTrace).toBeUndefined();++ // Ensure the freshly-inserted event is queryable before mutating.+ await waitForExpect(async () => {+ const eventTrace = await getTraceByIdFromEventsTable({+ projectId,+ traceId,+ renderingProps: { truncated: false, shouldJsonParse: true },+ });+ expect(eventTrace?.id).toBe(traceId);+ });++ const result = await caller.traces.publish({+ projectId,+ traceId,+ public: true,+ });++ expect(result).toBeDefined();+ expect(result?.id).toEqual(traceId);+ expect(result?.public).toBe(true);++ await waitForExpect(async () => {+ const eventTraceFull = await getTraceByIdFromEventsTable({+ projectId,+ traceId,+ renderingProps: {+ truncated: false,+ shouldJsonParse: true,+ },+ });+ expect(eventTraceFull).toBeDefined();+ expect(eventTraceFull?.public).toBe(true);+ });+ });+});diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.tsindex 6f7347a9ce..671c2ca654 100644--- a/web/src/__tests__/server/traces-trpc.servertest.ts+++ b/web/src/__tests__/server/traces-trpc.servertest.ts@@ -7,7 +7,7 @@ import {createTracesCh,createTraceScore,createScoresCh,- getTraceById,+ getTraceByIdFromTracesTable,createEventsCh,createEvent,getTraceByIdFromEventsTable,@@ -722,7 +722,8 @@ describe("traces trpc", () => {});describe("traces flags", () => {- const useEventsTable = env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS === "true";+ const useEventsTable =+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";it("should bookmark a trace", async () => {// Create a trace that is not bookmarkedconst trace = createTrace({@@ -745,7 +746,7 @@ describe("traces trpc", () => {]);}- const cleanTrace = await getTraceById({+ const cleanTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,clickhouseFeatureTag: "tracing-test",@@ -766,7 +767,7 @@ describe("traces trpc", () => {expect(result?.bookmarked).toBe(true);// Verify the trace is bookmarked in the database- const updatedTrace = await getTraceById({+ const updatedTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,clickhouseFeatureTag: "tracing-test",@@ -826,7 +827,7 @@ describe("traces trpc", () => {]);}- const cleanTrace = await getTraceById({+ const cleanTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,clickhouseFeatureTag: "tracing-test",@@ -847,7 +848,7 @@ describe("traces trpc", () => {expect(result?.public).toBe(true);// Verify the trace is public in the database- const updatedTrace = await getTraceById({+ const updatedTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,clickhouseFeatureTag: "tracing-test",diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.tsindex 21a9a71658..e9abd9ffa6 100644--- a/web/src/components/layouts/app-layout/utils/navigationFilters.ts+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.ts@@ -79,9 +79,7 @@ export const filters = {}if (route.featureFlag === "v4BetaToggleVisible") {- const isDev = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV";- const canToggleV4 = isDev || ctx.session?.user?.canToggleV4 === true;- return canToggleV4 && ctx.isLangfuseCloud ? route : null;+ return ctx.session?.user?.canToggleV4 === true ? route : null;}const hasFlag =diff --git a/web/src/env.mjs b/web/src/env.mjsindex fa3c401cdc..7f39bbffaa 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -420,27 +420,22 @@ export const env = createEnv({LANGFUSE_API_TRACES_DEFAULT_FIELDS: z.string().optional(),LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS: z.string().optional(),- // Legacy tracing search controls- LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH: z- .enum(["true", "false"])- .default("false"),-- // Events table migration- LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS: z+ // V4 preview opt-in. See LFE-9778.+ LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN: z.enum(["true", "false"]).default("false"),- // Events table for UI/tRPC routes (separate from public API flag)- LANGFUSE_ENABLE_EVENTS_TABLE_UI: z.enum(["true", "false"]).default("false"),-- LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS: z- .enum(["true", "false"])- .default("false"),-- // v2 APIs (events table based) - disabled by default for self-hosters- LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS: z+ // Legacy tracing search controls+ LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH: z.enum(["true", "false"]).default("false"),+ // V4 write mode. Mirrors worker/src/env.ts so the web package can gate+ // public API routes that rely on the legacy traces/observations tables.+ // The worker owns the writes; the web only needs to know whether legacy+ // tables are still being populated to decide whether to serve reads.+ LANGFUSE_MIGRATION_V4_WRITE_MODE: z+ .enum(["legacy", "dual", "events_only"])+ .default("legacy"),// Blocked users for chat completion API (userId:reason format)LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION: z@@ -843,18 +838,13 @@ export const env = createEnv({process.env.LANGFUSE_API_TRACES_DEFAULT_FIELDS,LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS:process.env.LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS,+ LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN:+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN,+ LANGFUSE_MIGRATION_V4_WRITE_MODE:+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE,// Legacy tracing search controlsLANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH:process.env.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH,- // Events table migration- LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS:- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS,- LANGFUSE_ENABLE_EVENTS_TABLE_UI:- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_UI,- LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS:- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS,- LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS:- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS,LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION:process.env.LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION,},diff --git a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.tsindex f574235123..c9b5839870 100644--- a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts+++ b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts@@ -60,7 +60,7 @@ const MAP_OBJECT_TYPE_TO_ACTION_PROPS: Record<[AnnotationQueueObjectType.OBSERVATION]: {actionId: ActionId.ObservationAddToAnnotationQueue,tableName:- env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? BatchExportTableName.Events: BatchExportTableName.Observations,},@@ -138,12 +138,13 @@ export const queueItemRouter = createTRPCRouter({if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {const clickhouseObservation =- env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? await getObservationByIdFromEventsTable({id: item.objectId,projectId: input.projectId,})- : await getObservationById({+ : // eslint-disable-next-line @typescript-eslint/no-deprecated+ await getObservationById({id: item.objectId,projectId: input.projectId,});@@ -230,7 +231,7 @@ export const queueItemRouter = createTRPCRouter({if (hasQueueItemsReferencingObservations) {traceIds =- env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? await getObservationsTraceIdsFromEventsTable({projectId: input.projectId,observationIds,diff --git a/web/src/features/annotation-queues/server/annotationQueuesRouter.ts b/web/src/features/annotation-queues/server/annotationQueuesRouter.tsindex e3af656843..fe34746546 100644--- a/web/src/features/annotation-queues/server/annotationQueuesRouter.ts+++ b/web/src/features/annotation-queues/server/annotationQueuesRouter.ts@@ -522,12 +522,13 @@ export const queueRouter = createTRPCRouter({if (item.objectType === AnnotationQueueObjectType.OBSERVATION) {const clickhouseObservation =- env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true"+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? await getObservationByIdFromEventsTable({id: item.objectId,projectId: input.projectId,})- : await getObservationById({+ : // eslint-disable-next-line @typescript-eslint/no-deprecated+ await getObservationById({id: item.objectId,projectId: input.projectId,});diff --git a/web/src/features/batch-actions/server/addToDatasetRouter.ts b/web/src/features/batch-actions/server/addToDatasetRouter.tsindex d7a039f363..c6d141e29e 100644--- a/web/src/features/batch-actions/server/addToDatasetRouter.ts+++ b/web/src/features/batch-actions/server/addToDatasetRouter.ts@@ -38,7 +38,8 @@ export const addToDatasetRouter = createTRPCRouter({const { projectId, query, config } = input;- const useEventsTable = env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true";+ const useEventsTable =+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";const tableName = useEventsTable? BatchTableNames.Events: BatchTableNames.Observations;diff --git a/web/src/features/batch-actions/server/runEvaluationRouter.ts b/web/src/features/batch-actions/server/runEvaluationRouter.tsindex 0d655774ab..6bae32ef03 100644--- a/web/src/features/batch-actions/server/runEvaluationRouter.ts+++ b/web/src/features/batch-actions/server/runEvaluationRouter.ts@@ -39,7 +39,7 @@ export const runEvaluationRouter = createTRPCRouter({sourceTable = BatchEvalSourceTable.EVENTS,} = input;- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS !== "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") {throw new TRPCError({code: "BAD_REQUEST",message: "Events table is not enabled for this instance.",diff --git a/web/src/features/comments/validateCommentReferenceObject.ts b/web/src/features/comments/validateCommentReferenceObject.tsindex c0de40d9df..ad25bd436f 100644--- a/web/src/features/comments/validateCommentReferenceObject.ts+++ b/web/src/features/comments/validateCommentReferenceObject.ts@@ -1,13 +1,10 @@import { CommentObjectType, type CreateCommentData } from "@langfuse/shared";import { type z } from "zod";-import { getObservationById, getTraceById } from "@langfuse/shared/src/server";--const isObservationOrTrace = (objectType: CommentObjectType) => {- return (- objectType === CommentObjectType.OBSERVATION ||- objectType === CommentObjectType.TRACE- );-};+import {+ getObservationById,+ getTraceById,+ getTracesIdentifierForSession,+} from "@langfuse/shared/src/server";export const validateCommentReferenceObject = async ({ctx,@@ -18,52 +15,48 @@ export const validateCommentReferenceObject = async ({}): Promise<{ errorMessage?: string }> => {const { objectId, objectType, projectId } = input;- if (isObservationOrTrace(objectType)) {- let clickhouseObject;- if (objectType === CommentObjectType.OBSERVATION) {- clickhouseObject = await getObservationById({+ let commentTarget;+ switch (objectType) {+ case CommentObjectType.OBSERVATION: {+ // eslint-disable-next-line @typescript-eslint/no-deprecated+ commentTarget = await getObservationById({id: objectId,projectId,});- } else {- clickhouseObject = await getTraceById({+ break;+ }+ case CommentObjectType.TRACE: {+ // eslint-disable-next-line @typescript-eslint/no-deprecated+ commentTarget = await getTraceById({traceId: objectId,projectId,});+ break;}-- return !!clickhouseObject- ? {}- : {- errorMessage: `Reference object, ${objectType}: ${objectId} not found in Clickhouse. Skipping creating comment.`,- };- } else {- const prismaModel =- objectType === CommentObjectType.SESSION- ? "traceSession"- : objectType === CommentObjectType.PROMPT- ? "prompt"- : null;-- if (!prismaModel) {- return {- errorMessage: `No prisma model for object type ${objectType}`,- };+ case CommentObjectType.SESSION: {+ commentTarget =+ // eslint-disable-next-line @typescript-eslint/no-deprecated+ (await getTracesIdentifierForSession(projectId, objectId)).shift();+ break;}-- const model = ctx.prisma[prismaModel];- const object = await model.findFirst({- where: {- id: objectId,- projectId,- },- });-- if (!object) {- return {- errorMessage: `No ${prismaModel} with id ${objectId} in project ${projectId}`,- };+ case CommentObjectType.PROMPT: {+ commentTarget = await ctx.prisma.prompt.findFirst({+ where: {+ id: objectId,+ projectId,+ },+ });+ break;+ }+ default: {+ const _exhaustiveCheck: never = objectType;+ throw new Error(`Invalid object type for comment: ${objectType}`);}- return {};}++ return Boolean(commentTarget)+ ? {}+ : {+ errorMessage: `Reference object, ${objectType}: ${objectId} not found. Skipping comment creation.`,+ };};diff --git a/web/src/features/datasets/server/publicDatasetService.ts b/web/src/features/datasets/server/publicDatasetService.tsindex 6ecbbd4567..8483d94547 100644--- a/web/src/features/datasets/server/publicDatasetService.ts+++ b/web/src/features/datasets/server/publicDatasetService.ts@@ -717,6 +717,7 @@ export const createDatasetRunItemForApi = async ({// Backwards compatibility: dataset run items were historically linked to observations, not traces.if (!traceId && observationId) {+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst observation = await getObservationById({id: observationId,projectId,diff --git a/web/src/features/evals/hooks/useEvalCapabilities.ts b/web/src/features/evals/hooks/useEvalCapabilities.tsindex b5c7ac5f1d..7b32e62495 100644--- a/web/src/features/evals/hooks/useEvalCapabilities.ts+++ b/web/src/features/evals/hooks/useEvalCapabilities.ts@@ -48,20 +48,37 @@ export function useEvalCapabilities(const evalCounts = api.evals.counts.useQuery({ projectId });const hasLegacyEvals = (evalCounts.data?.legacyConfigCount ?? 0) > 0;- // Only hide legacy options for new cloud users (canToggleV4 = false)- // Non-cloud deployments always see legacy options- // Use === true to default to false while session is loading, preventing flash of legacy options- // New users (canToggleV4 = false) default to observation-level evals regardless of v3/v4+ // The legacy eval experience depends on whether the deployment still writes+ // the legacy tables and on the user's rollout cohort. Use === true / explicit+ // mode checks so we default to hidden while the session is loading, which+ // prevents a flash of legacy options.const { isLangfuseCloud } = useLangfuseCloudRegion();const canToggleV4 = session?.user?.canToggleV4 === true;+ const v4WriteMode = session?.environment?.v4WriteMode;++ // Whether a *new* config may use the legacy experience (independent of+ // hasLegacyEvals, which always keeps legacy visible so existing legacy+ // evaluators stay manageable):+ // - events_only: legacy tables are no longer written → no new legacy evals.+ // - dual: self-hosted deployments always allow legacy; on Cloud only cohorts+ // that can still toggle V4 (orgs created before the rollout cutoff).+ // - legacy: legacy is the only experience.+ const modeAllowsNewLegacy =+ v4WriteMode === "events_only"+ ? false+ : v4WriteMode === "dual"+ ? isLangfuseCloud+ ? canToggleV4+ : true+ : v4WriteMode === "legacy"; // legacy → true; undefined (loading) → falsereturn {isNewCompatible: isOtel,// True when v4 beta is enabled (SDK check query was run)compatibilityCheckWasPerformed: isBetaEnabled,- // Allow legacy if: not code eval AND (not cloud OR user has legacy evals OR user can toggle v4)- allowLegacy:- !isCodeEvalConfig && (!isLangfuseCloud || hasLegacyEvals || canToggleV4),+ // Allow legacy if: not a code eval AND (user has legacy evals to manage OR+ // the deployment mode/cohort offers the legacy experience).+ allowLegacy: !isCodeEvalConfig && (hasLegacyEvals || modeAllowsNewLegacy),// Allow propagation filters only when using OTEL and spans are propagatingallowPropagationFilters: isOtel && isPropagating,isLoading:diff --git a/web/src/features/evals/server/codeEvalTestRun.ts b/web/src/features/evals/server/codeEvalTestRun.tsindex 2c8ac489c1..9586f9e2a8 100644--- a/web/src/features/evals/server/codeEvalTestRun.ts+++ b/web/src/features/evals/server/codeEvalTestRun.ts@@ -239,7 +239,7 @@ async function getObservationForEvalById(params: {shouldReadFromObservationsTable?: boolean;}): Promise<ObservationForEval> {if (- env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS !== "true" ||+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true" ||params.shouldReadFromObservationsTable) {return getObservationForEvalByIdFromLegacyObservations(params);@@ -291,6 +291,7 @@ async function getObservationForEvalByIdFromLegacyObservations(params: {traceId: string;startTime: Date;}): Promise<ObservationForEval> {+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst observation = await getObservationById({projectId: params.projectId,id: params.id,diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.tsindex acb3d57e4d..7f5d184659 100644--- a/web/src/features/evals/server/router.ts+++ b/web/src/features/evals/server/router.ts@@ -369,7 +369,7 @@ const assertCodeEvalJobConfigTestSucceeds = async ({const parsedMapping = z.array(observationVariableMapping).parse(mapping);- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {const result = await runCodeEvalTestForJobConfig({prisma,orgId,diff --git a/web/src/features/events/components/V4PromoBanner.tsx b/web/src/features/events/components/V4PromoBanner.tsxindex f4072d60e0..cf0d250351 100644--- a/web/src/features/events/components/V4PromoBanner.tsx+++ b/web/src/features/events/components/V4PromoBanner.tsx@@ -12,7 +12,6 @@ import {import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { V4IntroDialog } from "@/src/features/events/components/V4IntroDialog";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";const CHANGELOG_URL ="https://langfuse.com/changelog/2026-03-10-simplify-for-scale";@@ -42,7 +41,6 @@ export function V4PromoBanner() {isLoading,} = useV4Beta();const capture = usePostHogClientCapture();- const { isLangfuseCloud } = useLangfuseCloudRegion();const { getTopBannerOffset } = useTopBanner();const [isDismissed, setIsDismissed] = useLocalStorage<boolean>(DISMISSED_STORAGE_KEY,@@ -53,7 +51,7 @@ export function V4PromoBanner() {const isAuthenticated = session.status === "authenticated";// Match the v4BetaToggleVisible logic from navigationFilters.ts.- const isToggleVisible = canToggleV4 && isLangfuseCloud;+ const isToggleVisible = canToggleV4;const pageMessage = PAGE_MESSAGES[router.pathname];const isVisible =diff --git a/web/src/features/mcp/features/metrics/index.ts b/web/src/features/mcp/features/metrics/index.tsindex 0276bee5a1..ce886cf672 100644--- a/web/src/features/mcp/features/metrics/index.ts+++ b/web/src/features/mcp/features/metrics/index.ts@@ -22,5 +22,6 @@ export const metricsFeature: McpFeatureModule = {allowInAppAgentKey: true,},],- isEnabled: async () => env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true",+ isEnabled: async () =>+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true",};diff --git a/web/src/features/mcp/features/observations/index.ts b/web/src/features/mcp/features/observations/index.tsindex cc9a27d71e..416e80f4b3 100644--- a/web/src/features/mcp/features/observations/index.ts+++ b/web/src/features/mcp/features/observations/index.ts@@ -52,5 +52,6 @@ export const observationsFeature: McpFeatureModule = {allowInAppAgentKey: true,},],- isEnabled: async () => env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true",+ isEnabled: async () =>+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true",};diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex 53be5d953f..e626bed76c 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -64,6 +64,14 @@ export type AuthedProjectAPIRouteConfig<* Only set this to true on non-mutating (GET) routes that should be callable by the in-app agent.*/allowInAppAgentKey?: boolean;+ /**+ * When true, this route returns 404 if LANGFUSE_MIGRATION_V4_WRITE_MODE is+ * "events_only". Set this on routes that read from the legacy traces or+ * observations ClickHouse tables without an events_full fallback — those+ * tables are no longer populated in events_only mode and would silently+ * return stale or empty data.+ */+ rejectInEventsOnlyMode?: boolean;fn: (params: {query: z.infer<TQuery>;body: z.infer<TBody>;@@ -288,6 +296,21 @@ export const createAuthedProjectAPIRoute = <routeConfig: AuthedProjectAPIRouteConfig<TQuery, TBody, TResponse>,): ((req: NextApiRequest, res: NextApiResponse) => Promise<void>) => {return async (req: NextApiRequest, res: NextApiResponse) => {+ // Short-circuit routes that read from legacy traces/observations tables+ // when the deployment is in events_only mode — those tables are no longer+ // populated, so the response would be stale or empty. Returning 404 keeps+ // the surface area consistent with "this endpoint is not available here".+ if (+ routeConfig.rejectInEventsOnlyMode &&+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only"+ ) {+ res.status(404).json({+ message:+ "This endpoint is not available on deployments running in Langfuse v4 events_only mode. Learn more about Langfuse v4 at: https://langfuse.com/docs/v4",+ });+ return;+ }+let auth: AuthHeaderValidVerificationResult & {scope: { projectId: string; accessLevel: RouteAccessLevel };};diff --git a/web/src/features/public-api/server/health-service.ts b/web/src/features/public-api/server/health-service.tsindex fd3b801cb5..a163807b5d 100644--- a/web/src/features/public-api/server/health-service.ts+++ b/web/src/features/public-api/server/health-service.ts@@ -1,4 +1,5 @@import { VERSION } from "@/src/constants";+import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";import {convertDateToClickhouseDateTime,@@ -45,52 +46,89 @@ export const runHealthCheck = async ({const now = new Date();const clickhouseNow = convertDateToClickhouseDateTime(now);- const traces = await measureAndReturn({- operationName: "healthCheckTraces",- projectId: "__CROSS_PROJECT__",- input: {- now: clickhouseNow,- },- fn: async (params: { now: string }) =>- queryClickhouse<{ id: string }>({- query: `- SELECT id- FROM traces- WHERE timestamp <= {now: DateTime64(3)}- AND timestamp >= {now: DateTime64(3)} - INTERVAL 3 MINUTE- LIMIT 1- `,- params,- tags: {- feature: "health-check",- type: "trace",- },- }),- });+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only") {+ // In events_only mode the legacy traces/observations tables are no+ // longer written, so they would always look stale. Ingestion+ // completeness is instead reflected by recent rows in events_core+ // (the query-optimized projection of events_full).+ const events = await measureAndReturn({+ operationName: "healthCheckEvents",+ projectId: "__CROSS_PROJECT__",+ input: {+ now: clickhouseNow,+ },+ fn: async (params: { now: string }) =>+ queryClickhouse<{ span_id: string }>({+ query: `+ SELECT span_id+ FROM events_core+ WHERE start_time <= {now: DateTime64(3)}+ AND start_time >= {now: DateTime64(3)} - INTERVAL 3 MINUTE+ LIMIT 1+ `,+ params,+ tags: {+ feature: "health-check",+ type: "event",+ },+ }),+ });- const observations = await queryClickhouse<{ id: string }>({- query: `- SELECT id- FROM observations- WHERE start_time <= {now: DateTime64(3)}- AND start_time >= {now: DateTime64(3)} - INTERVAL 3 MINUTE- LIMIT 1- `,- params: {- now: clickhouseNow,- },- tags: {- feature: "health-check",- type: "observation",- },- });+ if (events.length === 0) {+ return {+ isHealthy: false,+ status: "No events within the last 3 minutes",+ version,+ };+ }+ } else {+ const traces = await measureAndReturn({+ operationName: "healthCheckTraces",+ projectId: "__CROSS_PROJECT__",+ input: {+ now: clickhouseNow,+ },+ fn: async (params: { now: string }) =>+ queryClickhouse<{ id: string }>({+ query: `+ SELECT id+ FROM traces+ WHERE timestamp <= {now: DateTime64(3)}+ AND timestamp >= {now: DateTime64(3)} - INTERVAL 3 MINUTE+ LIMIT 1+ `,+ params,+ tags: {+ feature: "health-check",+ type: "trace",+ },+ }),+ });- if (traces.length === 0 || observations.length === 0) {- return {- isHealthy: false,- status: `No ${traces.length === 0 ? "traces" : "observations"} within the last 3 minutes`,- version,- };+ const observations = await queryClickhouse<{ id: string }>({+ query: `+ SELECT id+ FROM observations+ WHERE start_time <= {now: DateTime64(3)}+ AND start_time >= {now: DateTime64(3)} - INTERVAL 3 MINUTE+ LIMIT 1+ `,+ params: {+ now: clickhouseNow,+ },+ tags: {+ feature: "health-check",+ type: "observation",+ },+ });++ if (traces.length === 0 || observations.length === 0) {+ return {+ isHealthy: false,+ status: `No ${traces.length === 0 ? "traces" : "observations"} within the last 3 minutes`,+ version,+ };+ }}}} catch (error) {diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.tsindex d2390ea0a2..f947fd6b33 100644--- a/web/src/pages/api/public/events.ts+++ b/web/src/pages/api/public/events.ts@@ -16,6 +16,9 @@ export default withMiddlewares({name: "Create Event",bodySchema: PostEventsV1Body,responseSchema: PostEventsV1Response,+ // Writes an observation-create event that lands in the legacy observations+ // ClickHouse table; events_only deployments expect OTel ingestion.+ rejectInEventsOnlyMode: true,fn: async ({ body, auth, res }) => {const event = {id: v4(),diff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.tsindex a8d88f80b6..5052e52af3 100644--- a/web/src/pages/api/public/generations.ts+++ b/web/src/pages/api/public/generations.ts@@ -19,6 +19,9 @@ export default withMiddlewares({bodySchema: PostGenerationsV1Body,responseSchema: PostGenerationsV1Response,rateLimitResource: "legacy-ingestion",+ // Writes an observation-create event that lands in the legacy observations+ // ClickHouse table; events_only deployments expect OTel ingestion.+ rejectInEventsOnlyMode: true,fn: async ({ body, auth, res }) => {const { prompt, completion, ...rest } = body;const event = {@@ -55,6 +58,7 @@ export default withMiddlewares({bodySchema: PatchGenerationsV1Body,responseSchema: PatchGenerationsV1Response,rateLimitResource: "legacy-ingestion",+ rejectInEventsOnlyMode: true,fn: async ({ body, auth, res }) => {const { generationId, prompt, completion, ...rest } = body;const event = {diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 7b7b5ce7f2..74a872a5b4 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -7,6 +7,7 @@ import {logger,getCurrentSpan,contextWithLangfuseProps,+ eventTypes,} from "@langfuse/shared/src/server";import { telemetry } from "@/src/features/telemetry";import { jsonSchema } from "@langfuse/shared";@@ -22,6 +23,7 @@ import { prisma } from "@langfuse/shared/src/db";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import * as opentelemetry from "@opentelemetry/api";+import { env } from "@/src/env.mjs";export const config = {api: {@@ -132,10 +134,20 @@ export default async function handler(}await telemetry();- const result = await processEventBatch(++ // V4 events_only mode: refuse trace/observation events because their+ // writes would land in the legacy ClickHouse tables this deployment no+ // longer reads. Scores and SDK logs are unaffected and pass through.+ // Reject per-event so a mixed batch still processes its score events.+ const { batchForProcessing, rejectedErrors } = filterBatchForEventsOnly(parsedSchema.data.batch,- authCheck,+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only",);++ const result = await processEventBatch(batchForProcessing, authCheck);+ if (rejectedErrors.length > 0) {+ result.errors = [...result.errors, ...rejectedErrors];+ }return res.status(207).json(result);});} catch (error: unknown) {@@ -173,3 +185,61 @@ export default async function handler(});}}++// Event types that may continue to ingest in V4 events_only mode. Scores keep+// their own ClickHouse table (no legacy traces/observations write); SDK logs+// are non-persisting.+const EVENTS_ONLY_ALLOWED_TYPES = new Set<string>([+ eventTypes.SCORE_CREATE,+ eventTypes.SDK_LOG,+ eventTypes.DATASET_RUN_ITEM_CREATE,+]);++function filterBatchForEventsOnly(+ batch: unknown[],+ isEventsOnlyMode: boolean,+): {+ batchForProcessing: unknown[];+ rejectedErrors: {+ id: string;+ status: number;+ message: string;+ error: string;+ }[];+} {+ if (!isEventsOnlyMode) {+ return { batchForProcessing: batch, rejectedErrors: [] };+ }++ const batchForProcessing: unknown[] = [];+ const rejectedErrors: {+ id: string;+ status: number;+ message: string;+ error: string;+ }[] = [];++ for (const event of batch) {+ const eventObj =+ typeof event === "object" && event !== null+ ? (event as { id?: unknown; type?: unknown })+ : null;+ const type =+ eventObj && typeof eventObj.type === "string" ? eventObj.type : null;+ const id =+ eventObj && typeof eventObj.id === "string" ? eventObj.id : "unknown";++ if (type && EVENTS_ONLY_ALLOWED_TYPES.has(type)) {+ batchForProcessing.push(event);+ } else {+ rejectedErrors.push({+ id,+ status: 400,+ message: "Event type not accepted",+ error: `Event type "${type ?? "unknown"}" is not accepted by /api/public/ingestion when LANGFUSE_MIGRATION_V4_WRITE_MODE is events_only. This endpoint only accepts score, log, and dataset-run-item events.`,+ });+ }+ }++ return { batchForProcessing, rejectedErrors };+}diff --git a/web/src/pages/api/public/metrics/daily.ts b/web/src/pages/api/public/metrics/daily.tsindex c2a430e9b3..7278fef22e 100644--- a/web/src/pages/api/public/metrics/daily.ts+++ b/web/src/pages/api/public/metrics/daily.ts@@ -15,6 +15,9 @@ export default withMiddlewares({querySchema: GetMetricsDailyV1Query,responseSchema: GetMetricsDailyV1Response,rateLimitResource: "public-api-daily-metrics-legacy",+ // Aggregates over the legacy traces and observations tables without an+ // events_full fallback.+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const filterProps = {projectId: auth.scope.projectId,diff --git a/web/src/pages/api/public/metrics/index.ts b/web/src/pages/api/public/metrics/index.tsindex eb08bbef7d..a5b5f41269 100644--- a/web/src/pages/api/public/metrics/index.ts+++ b/web/src/pages/api/public/metrics/index.ts@@ -16,6 +16,9 @@ export default withMiddlewares(rateLimitResource: "public-api-metrics",querySchema: GetMetricsV1Query,responseSchema: GetMetricsV1Response,+ // v1 metrics executes QueryBuilder against the legacy traces/observations+ // tables; the v2 endpoint at /api/public/v2/metrics targets events_full.+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {try {// Extract the parsed query objectdiff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].tsindex c5d4d7088a..faf92f2af2 100644--- a/web/src/pages/api/public/observations/[observationId].ts+++ b/web/src/pages/api/public/observations/[observationId].ts@@ -15,7 +15,6 @@ import {getObservationById,getObservationByIdFromEventsTable,} from "@langfuse/shared/src/server";-import { env } from "@/src/env.mjs";export default withMiddlewares({@@ -24,20 +23,16 @@ export default withMiddlewares(allowInAppAgentKey: true,querySchema: GetObservationV1Query,responseSchema: GetObservationV1Response,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {- // Use events table if query parameter is explicitly set, otherwise use environment variable- const useEventsTable =- query.useEventsTable !== undefined && query.useEventsTable !== null- ? query.useEventsTable === true- : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;-- const clickhouseObservation = useEventsTable+ const clickhouseObservation = query.useEventsTable? await getObservationByIdFromEventsTable({id: query.observationId,projectId: auth.scope.projectId,fetchWithInputOutput: true,})- : await getObservationById({+ : // eslint-disable-next-line @typescript-eslint/no-deprecated+ await getObservationById({id: query.observationId,projectId: auth.scope.projectId,fetchWithInputOutput: true,diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.tsindex 103f572c2a..c36b5e24cf 100644--- a/web/src/pages/api/public/observations/index.ts+++ b/web/src/pages/api/public/observations/index.ts@@ -3,7 +3,6 @@ import {getObservationsFromEventsTableForPublicApi,getObservationsCountFromEventsTableForPublicApi,} from "@langfuse/shared/src/server";-import { env } from "@/src/env.mjs";import {LEGACY_PUBLIC_API_OBSERVATIONS_CLICKHOUSE_RESOURCE_ERROR_MESSAGE,@@ -28,6 +27,7 @@ export default withMiddlewares(allowInAppAgentKey: true,querySchema: GetObservationsV1Query,responseSchema: GetObservationsV1Response,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const filterProps = {projectId: auth.scope.projectId,@@ -46,13 +46,7 @@ export default withMiddlewares(advancedFilters: query.filter,};- // Use events table if query parameter is explicitly set, otherwise use environment variable- const useEventsTable =- query.useEventsTable !== undefined && query.useEventsTable !== null- ? query.useEventsTable === true- : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;-- if (useEventsTable) {+ if (query.useEventsTable) {const [items, count] = await Promise.all([getObservationsFromEventsTableForPublicApi(filterProps),getObservationsCountFromEventsTableForPublicApi(filterProps),diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].tsindex aa469b34fb..685a426d6d 100644--- a/web/src/pages/api/public/scores/[scoreId].ts+++ b/web/src/pages/api/public/scores/[scoreId].ts@@ -16,6 +16,7 @@ export default withMiddlewares({name: "Get Score",querySchema: GetScoreQueryV1,responseSchema: GetScoreResponseV1,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const scoresApiService = new ScoresApiService("v1");const score = await scoresApiService.getScoreById({diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 04fe7a3300..df4800e0fa 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -56,6 +56,7 @@ export default withMiddlewares({name: "/api/public/scores",querySchema: GetScoresQueryV1,responseSchema: GetScoresResponseV1,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const scoresApiService = new ScoresApiService("v1");diff --git a/web/src/pages/api/public/sessions/[sessionId].ts b/web/src/pages/api/public/sessions/[sessionId].tsindex 208f140700..f066eb1423 100644--- a/web/src/pages/api/public/sessions/[sessionId].ts+++ b/web/src/pages/api/public/sessions/[sessionId].ts@@ -13,6 +13,9 @@ export default withMiddlewares({name: "Get Session",querySchema: GetSessionV1Query,responseSchema: GetSessionV1Response,+ // Reads from the legacy traces ClickHouse table via getTracesBySessionId,+ // which has no events_full fallback.+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const { sessionId } = query;const session = await prisma.traceSession.findUnique({diff --git a/web/src/pages/api/public/sessions/index.ts b/web/src/pages/api/public/sessions/index.tsindex 4f19ece7c4..10941b1598 100644--- a/web/src/pages/api/public/sessions/index.ts+++ b/web/src/pages/api/public/sessions/index.ts@@ -11,6 +11,7 @@ export default withMiddlewares({name: "Get Sessions",querySchema: GetSessionsV1Query,responseSchema: GetSessionsV1Response,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const { fromTimestamp, toTimestamp, limit, page, environment } = query;diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.tsindex 8490dbdcb1..5894901ae1 100644--- a/web/src/pages/api/public/spans.ts+++ b/web/src/pages/api/public/spans.ts@@ -18,6 +18,9 @@ export default withMiddlewares({name: "Create Span (Legacy)",bodySchema: PostSpansV1Body,responseSchema: PostSpansV1Response,+ // Writes an observation-create event that lands in the legacy observations+ // ClickHouse table; events_only deployments expect OTel ingestion.+ rejectInEventsOnlyMode: true,fn: async ({ body, auth, res }) => {const event = {id: v4(),@@ -50,6 +53,7 @@ export default withMiddlewares({name: "Update Span (Legacy)",bodySchema: PatchSpansV1Body,responseSchema: PatchSpansV1Response,+ rejectInEventsOnlyMode: true,fn: async ({ body, auth, res }) => {const event = {id: v4(),diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].tsindex 1b43b4e9fd..c8c75c888b 100644--- a/web/src/pages/api/public/traces/[traceId].ts+++ b/web/src/pages/api/public/traces/[traceId].ts@@ -34,6 +34,7 @@ export default withMiddlewares(name: "Get Single Trace",querySchema: GetTraceV1Query,responseSchema: GetTraceV1Response,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const { traceId } = query;@@ -55,6 +56,7 @@ export default withMiddlewares(const includeScores = requestedFields.includes("scores");const includeMetrics = requestedFields.includes("metrics");+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst trace = await getTraceById({traceId,projectId: auth.scope.projectId,diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex 827e99baa2..759f1111ea 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -38,6 +38,9 @@ export default withMiddlewares(bodySchema: PostTracesV1Body,responseSchema: PostTracesV1Response, // Adjust this if you have a specific response schemarateLimitResource: "legacy-ingestion",+ // Legacy POST writes a trace-create event that lands in the legacy traces+ // ClickHouse table; events_only deployments expect OTel ingestion.+ rejectInEventsOnlyMode: true,fn: async ({ body, auth, res }) => {await telemetry();const event = {@@ -69,6 +72,7 @@ export default withMiddlewares(name: "Get Traces",querySchema: GetTracesV1Query,responseSchema: GetTracesV1Response,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {// Api-performance controls.// 1. Reject if no date range and rejection is enabled@@ -123,13 +127,7 @@ export default withMiddlewares(toTimestamp: query.toTimestamp ?? undefined,};- // Use events table if query parameter is explicitly set, otherwise use environment variable- const useEventsTable =- query.useEventsTable !== undefined && query.useEventsTable !== null- ? query.useEventsTable === true- : env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true";-- if (useEventsTable) {+ if (query.useEventsTable) {const [items, count] = await Promise.all([getTracesFromEventsTableForPublicApi({...filterProps,diff --git a/web/src/pages/api/public/v2/metrics.ts b/web/src/pages/api/public/v2/metrics.tsindex d2fb00bbb7..235ab6fbd1 100644--- a/web/src/pages/api/public/v2/metrics.ts+++ b/web/src/pages/api/public/v2/metrics.ts@@ -18,9 +18,9 @@ export default withMiddlewares({querySchema: GetMetricsV2Query,responseSchema: GetMetricsV2Response,fn: async ({ query, auth }) => {- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS !== "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") {throw new LangfuseNotFoundError(- "v2 APIs are currently in beta and only available on Langfuse Cloud",+ "The metrics v2 API is only available in a Langfuse v4 write mode. Learn more at: https://langfuse.com/docs/v4",);}diff --git a/web/src/pages/api/public/v2/observations/index.ts b/web/src/pages/api/public/v2/observations/index.tsindex cf81801756..f5359310b7 100644--- a/web/src/pages/api/public/v2/observations/index.ts+++ b/web/src/pages/api/public/v2/observations/index.ts@@ -18,9 +18,9 @@ export default withMiddlewares({querySchema: GetObservationsV2Query,responseSchema: GetObservationsV2Response,fn: async ({ query, auth }) => {- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS !== "true") {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") {throw new LangfuseNotFoundError(- "v2 APIs are currently in beta and only available on Langfuse Cloud",+ "The observations v2 API is only available in a Langfuse v4 write mode. Learn more at: https://langfuse.com/docs/v4",);}diff --git a/web/src/pages/api/public/v2/scores/[scoreId].ts b/web/src/pages/api/public/v2/scores/[scoreId].tsindex 79bf537fbe..618c643563 100644--- a/web/src/pages/api/public/v2/scores/[scoreId].ts+++ b/web/src/pages/api/public/v2/scores/[scoreId].ts@@ -14,6 +14,7 @@ export default withMiddlewares({name: "Get Score",querySchema: GetScoreQueryV2,responseSchema: GetScoreResponseV2,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {const scoresApiService = new ScoresApiService("v2");const score = await scoresApiService.getScoreById({diff --git a/web/src/pages/api/public/v2/scores/index.ts b/web/src/pages/api/public/v2/scores/index.tsindex 09f4789cc4..6cdfe34722 100644--- a/web/src/pages/api/public/v2/scores/index.ts+++ b/web/src/pages/api/public/v2/scores/index.ts@@ -14,6 +14,7 @@ export default withMiddlewares({name: "/api/public/scores",querySchema: GetScoresQueryV2,responseSchema: GetScoresResponseV2,+ rejectInEventsOnlyMode: true,fn: async ({ query, auth }) => {// Validate that trace filters are not used when trace field is excludedconst requestedFields = query.fields ?? ["score", "trace"];diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.tsindex c0e2c45dbf..ca0ad60b5e 100644--- a/web/src/server/api/routers/comments.ts+++ b/web/src/server/api/routers/comments.ts@@ -318,7 +318,8 @@ export const commentsRouter = createTRPCRouter({input.projectId,input.sessionId,)- : await getTracesIdentifierForSession(input.projectId, input.sessionId);+ : // eslint-disable-next-line @typescript-eslint/no-deprecated+ await getTracesIdentifierForSession(input.projectId, input.sessionId);const allTraceCommentCounts = await ctx.prisma.$queryRaw<Array<{ objectId: string; count: bigint }>@@ -356,7 +357,8 @@ export const commentsRouter = createTRPCRouter({input.projectId,input.sessionId,)- : await getTracesIdentifierForSession(input.projectId, input.sessionId);+ : // eslint-disable-next-line @typescript-eslint/no-deprecated+ await getTracesIdentifierForSession(input.projectId, input.sessionId);const traceIds = clickhouseTraces.map((t) => t.id);diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.tsindex 930ab3bd6e..b584ddc149 100644--- a/web/src/server/api/routers/observations.ts+++ b/web/src/server/api/routers/observations.ts@@ -30,6 +30,7 @@ export const observationsRouter = createTRPCRouter({shouldJsonParse: false,},};+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst obs = await getObservationById(queryOpts);if (!obs) {throw new LangfuseNotFoundError(diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 4e515aacf1..c12e95de66 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -507,6 +507,7 @@ export const scoresRouter = createTRPCRouter({};if (inflatedParams.traceId) {+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst clickhouseTrace = await getTraceById({traceId: inflatedParams.traceId,projectId: input.projectId,@@ -523,6 +524,7 @@ export const scoresRouter = createTRPCRouter({}} else if (inflatedParams.sessionId) {// We consider no longer writing all sessions into postgres, hence we should search for traces with the session id+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst traceIdentifiers = await getTracesIdentifierForSession(input.projectId,inflatedParams.sessionId,@@ -675,6 +677,7 @@ export const scoresRouter = createTRPCRouter({};if (inflatedParams.traceId) {+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst clickhouseTrace = await getTraceById({traceId: inflatedParams.traceId,projectId: input.projectId,@@ -691,6 +694,7 @@ export const scoresRouter = createTRPCRouter({}} else if (inflatedParams.sessionId) {// We consider no longer writing all sessions into postgres, hence we should search for traces with the session id+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst traceIdentifiers = await getTracesIdentifierForSession(input.projectId,inflatedParams.sessionId,@@ -932,6 +936,7 @@ export const scoresRouter = createTRPCRouter({scope: "scores:CUD",});+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst clickhouseTrace = await getTraceById({traceId: input.traceId,projectId: input.projectId,diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex e21ae1913f..33f25989f8 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -21,7 +21,6 @@ import {type ScoreDomain,LISTABLE_SCORE_TYPES,} from "@langfuse/shared";-import { Prisma } from "@langfuse/shared/src/db";import { TRPCError } from "@trpc/server";import Decimal from "decimal.js";import {@@ -39,7 +38,6 @@ import {getCostForTraces,getTracesGroupedByUsers,getPublicSessionsFilter,- logger,getSessionsWithMetrics,hasAnySession,getScoresForSessions,@@ -91,6 +89,7 @@ const handleGetSessionById = async (input: {});}+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst clickhouseTraces = await getTracesIdentifierForSession(input.projectId,input.sessionId,@@ -676,21 +675,7 @@ export const sessionRouter = createTRPCRouter({}),).query(async ({ input, ctx }) => {- const postgresSession = await ctx.prisma.traceSession.findFirst({- where: {- id: input.sessionId,- projectId: input.projectId,- },- });-- if (!postgresSession) {- throw new TRPCError({- code: "NOT_FOUND",- message: "Session not found in project",- });- }-- const [scores, sessionMetrics] = await Promise.all([+ const [scores, sessionMetrics, postgresSession] = await Promise.all([getScoresForSessions({projectId: input.projectId,sessionIds: [input.sessionId],@@ -699,8 +684,25 @@ export const sessionRouter = createTRPCRouter({projectId: input.projectId,sessionIds: [input.sessionId],}).then((rows) => rows[0]),+ ctx.prisma.traceSession.findFirst({+ where: {+ id: input.sessionId,+ projectId: input.projectId,+ },+ select: {+ bookmarked: true,+ public: true,+ },+ }),]);+ if (!sessionMetrics) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Session not found in project",+ });+ }+const validatedScores: ScoreDomain[] = filterAndValidateDbScoreList({scores,dataTypes: LISTABLE_SCORE_TYPES,@@ -708,7 +710,10 @@ export const sessionRouter = createTRPCRouter({});return {- ...postgresSession,+ id: input.sessionId,+ projectId: input.projectId,+ bookmarked: postgresSession?.bookmarked ?? false,+ public: postgresSession?.public ?? false,users:sessionMetrics?.user_ids?.filter((userId) => userId !== null && userId !== "",@@ -828,49 +833,36 @@ export const sessionRouter = createTRPCRouter({}),).mutation(async ({ input, ctx }) => {- try {- throwIfNoProjectAccess({- session: ctx.session,- projectId: input.projectId,- scope: "objects:bookmark",- });+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "objects:bookmark",+ });- await auditLog({- session: ctx.session,- resourceType: "session",- resourceId: input.sessionId,- action: "bookmark",- after: input.bookmarked,- });+ await auditLog({+ session: ctx.session,+ resourceType: "session",+ resourceId: input.sessionId,+ action: "bookmark",+ after: input.bookmarked,+ });- const session = await ctx.prisma.traceSession.update({- where: {- id_projectId: {- id: input.sessionId,- projectId: input.projectId,- },- },- data: {- bookmarked: input.bookmarked,+ return ctx.prisma.traceSession.upsert({+ where: {+ id_projectId: {+ id: input.sessionId,+ projectId: input.projectId,},- });- return session;- } catch (error) {- logger.error("Unable to call sessions.bookmark", error);- if (- error instanceof Prisma.PrismaClientKnownRequestError &&- error.code === "P2025" // Record to update not found- )- throw new TRPCError({- code: "NOT_FOUND",- message: "Session not found in project",- });- else {- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- });- }- }+ },+ create: {+ id: input.sessionId,+ projectId: input.projectId,+ bookmarked: input.bookmarked,+ },+ update: {+ bookmarked: input.bookmarked,+ },+ });}),publish: protectedProjectProcedure.input(@@ -893,14 +885,19 @@ export const sessionRouter = createTRPCRouter({action: "publish",after: input.public,});- return ctx.prisma.traceSession.update({+ return ctx.prisma.traceSession.upsert({where: {id_projectId: {id: input.sessionId,projectId: input.projectId,},},- data: {+ create: {+ id: input.sessionId,+ projectId: input.projectId,+ public: input.public,+ },+ update: {public: input.public,},});diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 30498f5b5f..90d5e87274 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -513,6 +513,7 @@ export const traceRouter = createTRPCRouter({let trace;+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst clickhouseTrace = await getTraceById({traceId: input.traceId,projectId: input.projectId,@@ -524,7 +525,7 @@ export const traceRouter = createTRPCRouter({const promises = [upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace)),];- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy") {promises.push(updateEvents(input.projectId,@@ -571,6 +572,7 @@ export const traceRouter = createTRPCRouter({after: input.public,});+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst clickhouseTrace = await getTraceById({traceId: input.traceId,projectId: input.projectId,@@ -589,7 +591,7 @@ export const traceRouter = createTRPCRouter({const promises = [upsertTrace(convertTraceDomainToClickhouse(clickhouseTrace)),];- if (env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS === "true") {+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy") {promises.push(updateEvents(input.projectId,diff --git a/web/src/server/api/routers/userAccount.ts b/web/src/server/api/routers/userAccount.tsindex 8ac16a88c5..3efc566e24 100644--- a/web/src/server/api/routers/userAccount.ts+++ b/web/src/server/api/routers/userAccount.ts@@ -131,12 +131,27 @@ export const userAccountRouter = createTRPCRouter({setV4BetaEnabled: authenticatedProcedure.input(z.object({ enabled: z.boolean() })).mutation(async ({ input, ctx }) => {- const isCloudDeployment = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);+ // Mirror the V4 preview gating in the auth.ts session callback so the+ // write path agrees with what the session reports. Availability is+ // driven by the write mode.+ const v4WriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);++ // In events_only mode the preview is mandatory and cannot be toggled off:+ // the legacy tables it would fall back to are no longer written. Ignore+ // the requested value so a stale client can't flip a user into broken+ // reads, and keep the returned session shape consistent with auth.ts.+ if (v4WriteMode === "events_only") {+ return {+ success: true,+ v4BetaEnabled: true,+ canToggleV4: false,+ };+ }- if (- !isCloudDeployment &&- process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "DEV"- ) {+ // In legacy mode the events tables are not written, so the preview has+ // nothing correct to read — it stays off and cannot be toggled.+ if (v4WriteMode === "legacy") {return {success: true,v4BetaEnabled: false,@@ -144,6 +159,33 @@ export const userAccountRouter = createTRPCRouter({};}+ // dual mode. On Cloud the date-based rollout applies (handled below) —+ // users auto-enabled by the rollout are locked on and cannot toggle off.+ // Self-hosted deployments are opt-in, but only once they have also set+ // ALLOW_PREVIEW_OPT_IN=true; otherwise feature paths still gated on that+ // flag would fall back to legacy tables while the core UI reads events,+ // so the toggle is not offered (mirrors the auth.ts session callback).+ if (!isLangfuseCloud) {+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN !== "true") {+ return {+ success: true,+ v4BetaEnabled: false,+ canToggleV4: false,+ };+ }++ await ctx.prisma.user.update({+ where: { id: ctx.session.user.id },+ data: { v4BetaEnabled: input.enabled },+ });++ return {+ success: true,+ v4BetaEnabled: input.enabled,+ canToggleV4: true,+ };+ }+const userRolloutState = await ctx.prisma.user.findUnique({where: { id: ctx.session.user.id },select: {diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex f4819f32de..3d0c295231 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -480,6 +480,7 @@ const enforceTraceAccess = t.middleware(async (opts) => {const fromTimestamp = result.data.fromTimestamp;const verbosity = result.data.verbosity;+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst clickhouseTrace = await getTraceById({traceId,projectId,@@ -586,7 +587,9 @@ const enforceSessionAccess = t.middleware(async (opts) => {const { sessionId, projectId } = result.data;- // trace sessions are stored in postgres. No need to check for clickhouse eligibility.+ // trace_sessions should be a sparse metadata side-table: a row only exists once a+ // session has been bookmarked or published.+ // If it's not marked as public, we fallback to the usual user-based project access check.const session = await ctx.prisma.traceSession.findFirst({where: {id: sessionId,@@ -597,22 +600,14 @@ const enforceSessionAccess = t.middleware(async (opts) => {},});- if (!session) {- logger.error(- `Session with id ${sessionId} not found for project ${projectId}`,- );- throw new TRPCError({- code: "NOT_FOUND",- message: "Session not found",- });- }+ const isPublicSession = session?.public ?? false;const userSessionProject = ctx.session?.user?.organizations.flatMap((org) => org.projects).find(({ id }) => id === projectId);if (- !session.public &&+ !isPublicSession &&!userSessionProject &&ctx.session?.user?.admin !== true) {diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex de6a2d0533..10e430c999 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -805,9 +805,29 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {span.setAttribute("langfuse.user.email", dbUser?.email ?? "");span.setAttribute("langfuse.user.id", dbUser?.id ?? "");- const isCloudDeploymentOrDev = Boolean(+ // V4 preview availability is governed by the write mode:+ // - events_only: the legacy traces/observations tables are no longer+ // written, so the events-aware UI is the only correct read path —+ // force the preview on for everyone and hide the toggle.+ // - legacy: the events tables are not written, so the preview cannot+ // read — keep it off and hide the toggle.+ // - dual: both table sets are written, so the preview is optional. On+ // Cloud we keep the date-based rollout (new orgs are auto-enabled+ // and locked on at signup/org-creation, older orgs may toggle).+ // Self-hosted dual deployments are opt-in, but only once they have+ // also set LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true —+ // otherwise feature paths still gated on that flag would silently+ // fall back to legacy tables while the core UI reads events.+ const v4WriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,);+ // In dual mode the preview is available on Cloud (governed by the+ // rollout below) or on self-hosted deployments that opted into the+ // preview read path via ALLOW_PREVIEW_OPT_IN.+ const dualPreviewAvailable =+ isLangfuseCloud ||+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";return {...session,@@ -817,6 +837,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {// Enables features that are only available under an enterprise license when self-hosting Langfuse// If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)selfHostedInstancePlan: getSelfHostedInstancePlanServerSide(),+ v4WriteMode,},user:dbUser !== null@@ -830,23 +851,31 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {: undefined,image: dbUser.image,admin: dbUser.admin,- v4BetaEnabled: isCloudDeploymentOrDev- ? dbUser.v4BetaEnabled- : false,- canToggleV4: isCloudDeploymentOrDev- ? canToggleV4({- userCreatedAt: dbUser.createdAt,- organizations: dbUser.organizationMemberships.map(- (orgMembership) => ({- id: orgMembership.organization.id,- createdAt: orgMembership.organization.createdAt,- }),- ),- excludedOrganizationIds: env.NEXT_PUBLIC_DEMO_ORG_ID- ? [env.NEXT_PUBLIC_DEMO_ORG_ID]- : [],- })- : false,+ v4BetaEnabled:+ v4WriteMode === "events_only"+ ? true+ : v4WriteMode === "dual" && dualPreviewAvailable+ ? dbUser.v4BetaEnabled+ : false,+ canToggleV4:+ v4WriteMode === "dual" && dualPreviewAvailable+ ? isLangfuseCloud+ ? canToggleV4({+ userCreatedAt: dbUser.createdAt,+ organizations: dbUser.organizationMemberships.map(+ (orgMembership) => ({+ id: orgMembership.organization.id,+ createdAt:+ orgMembership.organization.createdAt,+ }),+ ),+ excludedOrganizationIds:+ env.NEXT_PUBLIC_DEMO_ORG_ID+ ? [env.NEXT_PUBLIC_DEMO_ORG_ID]+ : [],+ })+ : true+ : false,canCreateOrganizations: canCreateOrganizations(dbUser.email,),diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 2a6c8c26ac..d841a8e654 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -23,6 +23,12 @@ declare module "next-auth" {enableExperimentalFeatures: boolean;// Enables features that are only available under an enterprise/commercial license when self-hosting LangfuseselfHostedInstancePlan: Plan | null;+ // V4 migration write mode. Mirrors LANGFUSE_MIGRATION_V4_WRITE_MODE so the+ // client can tell whether the legacy traces/observations tables are still+ // written and gate the V4 preview / legacy experiences accordingly.+ // Optional so existing session mocks need not set it; the real session+ // callback always populates it.+ v4WriteMode?: "legacy" | "dual" | "events_only";};}diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.tsindex 2f74a48f27..4ea05f5b21 100644--- a/worker/src/__tests__/batchAction.test.ts+++ b/worker/src/__tests__/batchAction.test.ts@@ -38,7 +38,7 @@ import waitForExpect from "wait-for-expect";import { Queue } from "bullmq";const maybeDescribe =- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.tsindex f0d9db3c1d..051794b9aa 100644--- a/worker/src/__tests__/batchExport.test.ts+++ b/worker/src/__tests__/batchExport.test.ts@@ -26,7 +26,7 @@ process.env.LANGFUSE_DATASET_SERVICE_READ_FROM_VERSIONED_IMPLEMENTATION =process.env.LANGFUSE_DATASET_SERVICE_WRITE_TO_VERSIONED_IMPLEMENTATION = "true";const maybeDescribe =- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex e5e0c23b17..29da09558c 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -50,7 +50,7 @@ import { encrypt } from "@langfuse/shared/encryption";// and at least azurite doesn't handle them gracefully.const maybeIt = env.LANGFUSE_USE_AZURE_BLOB === "true" ? it.skip : it;const maybeDescribe =- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"? describe: describe.skip;diff --git a/worker/src/__tests__/projectDeletionProcessing.test.ts b/worker/src/__tests__/projectDeletionProcessing.test.tsindex 083d3462bf..93ba6face8 100644--- a/worker/src/__tests__/projectDeletionProcessing.test.ts+++ b/worker/src/__tests__/projectDeletionProcessing.test.ts@@ -1,5 +1,5 @@import { expect, it, describe, beforeAll, beforeEach, afterEach } from "vitest";-import { env } from "../env";+import { env, v4WritesToEventsTable } from "../env";import { randomUUID } from "crypto";import {convertDateToClickhouseDateTime,@@ -34,8 +34,7 @@ describe("ProjectDeletionProcessingJob", () => {let s3Prefix: string | null = null;const orgId = "seed-org-id";- const maybeEventsIt =- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" ? it : it.skip;+ const maybeEventsIt = v4WritesToEventsTable(env) ? it : it.skip;beforeAll(() => {storageService = StorageServiceFactory.getInstance({diff --git a/worker/src/app.ts b/worker/src/app.tsindex ad2f5dde9a..855b113c15 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -46,7 +46,7 @@ import {LLMAsJudgeExecutionQueue,CodeEvalExecutionQueue,} from "@langfuse/shared/src/server";-import { env } from "./env";+import { env, v4WritesToEventsTable } from "./env";import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";import { BackgroundMigrationManager } from "./backgroundMigrations/backgroundMigrationManager";import { prisma } from "@langfuse/shared/src/db";@@ -608,9 +608,11 @@ if (env.QUEUE_CONSUMER_ENTITY_CHANGE_QUEUE_IS_ENABLED === "true") {);}+// The event-propagation queue is required whenever we write to events_full+// (V4 WRITE_MODE in {dual, events_only}).if (env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true" &&- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ v4WritesToEventsTable(env)) {// Instantiate the queue to trigger scheduled jobsEventPropagationQueue.getInstance();@@ -639,10 +641,10 @@ export const batchProjectCleaners: BatchProjectCleaner[] = [];if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {for (const table of BATCH_DELETION_TABLES) {- // Only start the events table cleaners if the events table experiment is enabled+ // Only start the events table cleaners when V4 write mode targets events_full.if ((table !== "events_full" && table !== "events_core") ||- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ v4WritesToEventsTable(env)) {const cleaner = new BatchProjectCleaner(table);batchProjectCleaners.push(cleaner);@@ -656,10 +658,10 @@ export const batchDataRetentionCleaners: BatchDataRetentionCleaner[] = [];if (env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_ENABLED === "true") {for (const table of BATCH_DATA_RETENTION_TABLES) {- // Only start the events table cleaners if the events table experiment is enabled+ // Only start the events table cleaners when V4 write mode targets events_full.if ((table !== "events_full" && table !== "events_core") ||- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ v4WritesToEventsTable(env)) {const cleaner = new BatchDataRetentionCleaner(table);batchDataRetentionCleaners.push(cleaner);diff --git a/worker/src/backgroundMigrations/backfillEventsHistoric.ts b/worker/src/backgroundMigrations/backfillEventsHistoric.tsdeleted file mode 100644index f5c240193b..0000000000--- a/worker/src/backgroundMigrations/backfillEventsHistoric.ts+++ /dev/null@@ -1,963 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- clickhouseClient,- commandClickhouse,- logger,- queryClickhouse,- pollQueryStatus,- getQueryError,- sleep,-} from "@langfuse/shared/src/server";-import { prisma } from "@langfuse/shared/src/db";-import { env } from "../env";-import { parseArgs } from "node:util";-import { randomUUID } from "crypto";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table-const backgroundMigrationId = "d8cf9f5e-747e-4ffe-8156-dec0eaebce9d";--// ============================================================================-// Types-// ============================================================================--export interface BaseChunkTodo {- id: string; // Unique chunk identifier (e.g., "obs-202510-0")- partition: string; // ClickHouse partition (e.g., "202510")- status: "pending" | "in_progress" | "completed" | "failed";- queryId?: string; // Client-generated UUID for tracking in system.query_log- startedAt?: string;- completedAt?: string;- error?: string;- retryCount?: number;-}--interface ChunkTodo extends BaseChunkTodo {- lowerBound: { projectId: string; traceId: string }; // From backfill_chunks table- upperBound: { projectId: string; traceId: string } | null; // null = end of partition-}--interface MigrationArgs {- concurrency?: number; // Default: 4- pollIntervalMs?: number; // Default: 30_000- maxRetries?: number; // Default: 3- retryFailed?: boolean; // Reset failed chunks to pending-}--interface MigrationState {- phase: "init" | "loading_chunks" | "backfill" | "completed";- chunksLoaded: boolean; // Whether chunks have been loaded from backfill_chunks- todos: ChunkTodo[];- activeQueries: string[]; // Currently running query IDs- config: MigrationArgs;-}--const DEFAULT_CONFIG: MigrationState["config"] = {- concurrency: 4,- pollIntervalMs: 30_000,- maxRetries: 3,-};--export type OnQueryCompleteCallback<T extends BaseChunkTodo> = (- todo: T,-- success: boolean,-- error?: string,-) => Promise<void>;--// ============================================================================-// Concurrent Query Manager-// ============================================================================--export class ConcurrentQueryManager<T extends BaseChunkTodo> {- private activeQueries: Map<string, T> = new Map();- private pollInterval: NodeJS.Timeout | null = null;- private isPolling = false;-- startPolling(- pollIntervalMs: number,- onComplete: OnQueryCompleteCallback<T>,- scheduleNext: () => Promise<void>,- ): void {- if (this.pollInterval) {- return; // Already polling- }-- this.pollInterval = setInterval(async () => {- if (this.isPolling) return; // Skip if previous poll still running- this.isPolling = true;-- try {- for (const [queryId, todo] of this.activeQueries) {- try {- const status = await pollQueryStatus(queryId);-- if (status === "completed") {- this.activeQueries.delete(queryId);- try {- await onComplete(todo, true);- await scheduleNext(); // Immediately schedule next- } catch (err) {- logger.error(- `[Backfill Events] Error in onComplete/scheduleNext for completed chunk ${todo.id}`,- err,- );- throw err;- }- } else if (status === "failed" || status === "not_found") {- this.activeQueries.delete(queryId);- const error =- status === "failed"- ? await getQueryError(queryId)- : "Query not found in query_log";- try {- await onComplete(todo, false, error);- await scheduleNext();- } catch (err) {- logger.error(- `[Backfill Events] Error in onComplete/scheduleNext for failed chunk ${todo.id}`,- err,- );- throw err;- }- }- // 'running' - continue polling- } catch (queryError) {- // Error while polling this specific query - log warning and continue polling- // Polling errors (e.g., timeouts) are transient and don't indicate query failure- logger.warn(- `[Backfill Events] Error polling query ${queryId} for chunk ${todo.id}, will retry on next poll cycle`,- queryError,- );- // Don't remove from activeQueries or call onComplete - just continue polling- }- }- } catch (error) {- // Unexpected error outside individual query handling- logger.error(- "[Backfill Events] Unexpected error during poll cycle",- error,- );- } finally {- this.isPolling = false;- }- }, pollIntervalMs);- }-- addQuery(todo: T, queryId: string): void {- this.activeQueries.set(queryId, todo);- }-- get activeCount(): number {- return this.activeQueries.size;- }-- stopPolling(): void {- if (this.pollInterval) {- clearInterval(this.pollInterval);- this.pollInterval = null;- }- }-}--// ============================================================================-// Helper Functions-// ============================================================================--export function generateQueryId(chunkId: string): string {- return `backfill-${chunkId}-${randomUUID().slice(0, 8)}`;-}--// ============================================================================-// Migration Class-// ============================================================================--export default class BackfillEventsHistoric implements IBackgroundMigration {- private isAborted = false;-- // ============================================================================- // State Management- // ============================================================================-- private async loadState(): Promise<MigrationState> {- const migration = await prisma.backgroundMigration.findUnique({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const defaultState: MigrationState = {- phase: "init",- chunksLoaded: false,- todos: [],- activeQueries: [],- config: { ...DEFAULT_CONFIG },- };-- if (!migration || !migration.state) {- return defaultState;- }-- const state = migration.state as Partial<MigrationState>;-- return {- phase: state.phase ?? defaultState.phase,- chunksLoaded: state.chunksLoaded ?? defaultState.chunksLoaded,- todos: state.todos ?? defaultState.todos,- activeQueries: state.activeQueries ?? defaultState.activeQueries,- config: {- ...DEFAULT_CONFIG,- ...state.config,- },- };- }-- private async updateState(state: MigrationState): Promise<void> {- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: state as any },- });- }-- // ============================================================================- // Prerequisite Validation- // ============================================================================-- private async validatePrerequisites(): Promise<{- valid: boolean;- reason?: string;- }> {- const requiredTables = [- "observations_pid_tid_sorting",- "traces_pid_tid_sorting",- "events_full",- "backfill_chunks",- ];-- for (const table of requiredTables) {- try {- const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM ${table} LIMIT 1`,- tags: {- feature: "background-migration",- operation: "validatePrerequisites",- table,- },- });- if (!result.length) {- return { valid: false, reason: `${table} table does not exist` };- }- } catch {- return {- valid: false,- reason: `${table} table does not exist or is not accessible`,- };- }- }-- // Verify backfill_chunks has data- const chunksCount = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM backfill_chunks`,- tags: {- feature: "background-migration",- operation: "validatePrerequisites",- table: "backfill_chunks",- },- });- if (chunksCount[0].count === "0") {- return {- valid: false,- reason:- "backfill_chunks table is empty - populate chunk boundaries first",- };- }-- return { valid: true };- }-- // ============================================================================- // Load Chunks from ClickHouse- // ============================================================================-- private async loadChunksFromClickhouse(): Promise<ChunkTodo[]> {- logger.info("[Backfill Events] Loading chunks from backfill_chunks table");-- const chunks = await queryClickhouse<{- chunk_id: string;- partition_id: string;- project_id: string;- trace_id: string;- is_last_chunk: string;- }>({- query: `- SELECT chunk_id, partition_id, project_id, trace_id, is_last_chunk- FROM backfill_chunks- ORDER BY partition_id, chunk_id- `,- tags: {- feature: "background-migration",- operation: "loadChunksFromClickhouse",- },- });-- const todos: ChunkTodo[] = [];-- // Group by partition and type to compute upper bounds- const grouped = new Map<string, typeof chunks>();- for (const chunk of chunks) {- const key = chunk.partition_id;- if (!grouped.has(key)) grouped.set(key, []);- grouped.get(key)!.push(chunk);- }-- for (const [, partitionChunks] of grouped) {- for (let i = 0; i < partitionChunks.length; i++) {- const chunk = partitionChunks[i];- const nextChunk = partitionChunks[i + 1];- const isLastChunk = chunk.is_last_chunk === "1";-- todos.push({- id: chunk.chunk_id,- partition: chunk.partition_id,- lowerBound: { projectId: chunk.project_id, traceId: chunk.trace_id },- upperBound:- isLastChunk || !nextChunk- ? null- : {- projectId: nextChunk.project_id,- traceId: nextChunk.trace_id,- },- status: "pending",- });- }- }-- logger.info(- `[Backfill Events] Loaded ${todos.length} chunks from backfill_chunks table`,- );-- return todos;- }-- // ============================================================================- // Recovery Logic- // ============================================================================-- /**- * Recovers in-progress todos from a previous run.- * Returns an array of todos that are still running and should be added to the query manager.- */- private async recoverInProgressTodos(- state: MigrationState,- ): Promise<ChunkTodo[]> {- const inProgress = state.todos.filter(- (t) => t.status === "in_progress" && t.queryId,- );-- if (inProgress.length === 0) {- return [];- }-- logger.info(- `[Backfill Events] Recovering ${inProgress.length} in-progress chunks`,- );-- const stillRunning: ChunkTodo[] = [];-- for (const todo of inProgress) {- try {- // Only check if query is still running in system.processes- // If not running, reset to pending - don't try to check query_log as it may timeout- const running = await queryClickhouse<{ query_id: string }>({- query: `- SELECT query_id- FROM clusterAllReplicas('default', 'system.processes')- WHERE query_id = {queryId: String}- LIMIT 1- `,- params: { queryId: todo.queryId! },- clickhouseConfigs: {- request_timeout: 60_000,- },- clickhouseSettings: {- skip_unavailable_shards: 1,- },- tags: {- feature: "background-migration",- operation: "recoverInProgressTodos",- },- });-- if (running.length > 0) {- // Query is still running on ClickHouse - track it in the manager- logger.info(- `[Backfill Events] Recovered chunk ${todo.id} as still running (query ${todo.queryId}), will continue tracking`,- );- stillRunning.push(todo);- } else {- // Query not in system.processes - reset to pending and retry- todo.status = "pending";- todo.queryId = undefined;- logger.warn(- `[Backfill Events] Recovered chunk ${todo.id} query not found in system.processes, resetting to pending`,- );- }- } catch (error) {- logger.error(- `[Backfill Events] Error during recovery polling for chunk ${todo.id}, resetting to pending`,- error,- );- todo.status = "pending";- todo.queryId = undefined;- }- }-- await this.updateState(state);- return stillRunning;- }-- // ============================================================================- // Query Building- // ============================================================================-- private buildQuery(todo: ChunkTodo): string {- const whereClause = todo.upperBound- ? `WHERE (o.project_id, o.trace_id) >= ('${todo.lowerBound.projectId}', '${todo.lowerBound.traceId}')- AND (o.project_id, o.trace_id) < ('${todo.upperBound.projectId}', '${todo.upperBound.traceId}')`- : `WHERE (o.project_id, o.trace_id) >= ('${todo.lowerBound.projectId}', '${todo.lowerBound.traceId}')`;-- // Conditionally filter out 'attributes' key from metadata- const metadataExpr =- env.LANGFUSE_EXPERIMENT_BACKFILL_EXCLUDE_ATTRIBUTES_KEY === "true"- ? `mapFilter((k, v) -> k != 'attributes', o.metadata)`- : `o.metadata`;-- return `- INSERT INTO events_full (- project_id, trace_id, span_id, parent_span_id, start_time, end_time,- name, type, environment, version, release, tags, public, bookmarked,- trace_name, user_id, session_id, 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, tool_definitions, tool_calls, tool_call_names,- input, output,- metadata_names, metadata_values, source,- blob_storage_file_path, event_bytes, created_at, updated_at, event_ts, is_deleted- )- SELECT- o.project_id,- o.trace_id,- o.id AS span_id,- if(o.id = o.trace_id, NULL, coalesce(o.parent_observation_id, concat('t-', o.trace_id))) AS parent_span_id,- o.start_time AS start_time,- o.end_time,- o.name,- o.type,- o.environment,- coalesce(o.version, t.version) as version,- coalesce(t.release, '') as release,- t.tags as tags,- t.public as public,- t.bookmarked as bookmarked,- coalesce(t.name, '') AS trace_name,- coalesce(t.user_id, '') AS user_id,- coalesce(t.session_id, '') AS session_id,- o.level,- coalesce(o.status_message, '') AS status_message,- o.completion_start_time,- o.prompt_id,- o.prompt_name,- o.prompt_version,- o.internal_model_id AS model_id,- o.provided_model_name,- coalesce(o.model_parameters, '{}') AS model_parameters,- o.provided_usage_details,- o.usage_details,- o.provided_cost_details,- o.cost_details,- o.tool_definitions,- o.tool_calls,- o.tool_call_names,-- coalesce(o.input, '') AS input,- coalesce(o.output, '') AS output,- mapKeys(${metadataExpr}) AS metadata_names,- mapValues(${metadataExpr}) AS metadata_values,- multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,- '' AS blob_storage_file_path,- 0 AS event_bytes,- o.created_at,- o.updated_at,- o.event_ts,- o.is_deleted- FROM observations_pid_tid_sorting o- LEFT ANY JOIN (select * from traces_pid_tid_sorting where _partition_id = '${todo.partition}') t- ON o.project_id = t.project_id AND o.trace_id = t.id- ${whereClause}- -- Conditionally filter for partitions if not "REST"- -- This allow us to have a catch all partition for older data- ${todo.partition !== "REST" ? `AND o._partition_id = '${todo.partition}'` : ""}- SETTINGS- join_algorithm = 'full_sorting_merge',- type_json_skip_duplicated_paths = 1- `;- }-- // ============================================================================- // Fire Query (with tracking)- // ============================================================================-- private async fireQuery(- query: string,- queryId: string,- retryCount: number = 0,- ): Promise<void> {- logger.info(`[Backfill Events] Firing query ${queryId}`);-- // Create AbortController to abort HTTP connection after query starts on server.- // This follows ClickHouse best practices for long-running queries:- // https://github.com/ClickHouse/clickhouse-js/blob/main/examples/long_running_queries_timeouts.ts- const abortController = new AbortController();-- // Apply memory-reducing settings on retries- const retrySettings =- retryCount > 1- ? {- max_threads: 1,- max_insert_threads: "1",- max_block_size: "2048",- }- : retryCount > 0- ? {- max_block_size: "4096",- }- : {};-- if (retryCount > 0) {- logger.info(- `[Backfill Events] Applying retry settings for query ${queryId}: ${JSON.stringify(retrySettings)} (retry ${retryCount})`,- );- }-- // Fire the query with abort signal. The query will continue on the server- // even after we abort the HTTP connection.- const queryPromise = commandClickhouse({- query,- tags: {- feature: "background-migration",- operation: "fireQuery",- queryId,- },- // clickhouseConfigs: {- // request_timeout: timeoutMs,- // },- clickhouseSettings: {- // send_progress_in_http_headers: 1,- // http_headers_progress_interval_ms: "30000",- ...retrySettings,- },- abortSignal: abortController.signal,- });-- // Wait a short time to ensure query is registered- await sleep(5000);-- // Verify query is running on server- try {- const status = await pollQueryStatus(queryId);- if (status === "not_found") {- // Query may have completed very quickly or failed to start- // Wait a bit more and check again- await sleep(15000);- const retryStatus = await pollQueryStatus(queryId);- if (retryStatus === "not_found") {- throw new Error(`Query ${queryId} failed to start on server`);- }- }- } catch (error) {- logger.error(- `[Backfill Events] Error verifying query ${queryId} started`,- error,- );- throw error; // Re-throw so the caller knows the query failed to start- }-- // Abort the HTTP connection now that the query is confirmed running on the server.- // This prevents "Broken pipe" errors from the connection timing out.- // The query continues executing on ClickHouse - we track completion via polling.- logger.info(- `[Backfill Events] Query ${queryId} confirmed running, aborting HTTP connection`,- );- abortController.abort();-- // Handle the expected abort error- queryPromise.catch((err) => {- // Abort errors are expected - log at debug level- if (err?.name === "AbortError" || err?.message?.includes("aborted")) {- logger.debug(- `[Backfill Events] Query ${queryId} HTTP connection aborted as expected`,- );- } else {- logger.info(- `[Backfill Events] Query ${queryId} promise rejected: ${err?.message}`,- err,- );- }- });- }-- // ============================================================================- // Validation- // ============================================================================-- async validate(- args: Record<string, unknown>,- attempts = 5,- ): Promise<{ valid: boolean; invalidReason: string | undefined }> {- // Ensure the background migration record exists- // TODO: Remove for golive- await prisma.backgroundMigration.upsert({- where: { id: backgroundMigrationId },- create: {- id: backgroundMigrationId,- name: "20251027_backfill_events_historic",- script: "backfillEventsHistoric",- args: {},- state: {},- },- update: {},- });-- // Check if ClickHouse credentials are configured- if (- !env.CLICKHOUSE_URL ||- !env.CLICKHOUSE_USER ||- !env.CLICKHOUSE_PASSWORD- ) {- return {- valid: false,- invalidReason:- "ClickHouse credentials must be configured to perform migration",- };- }-- // Check if ClickHouse events_full table exists- const tables = await clickhouseClient().query({- query: "SHOW TABLES",- });- const tableNames = (await tables.json()).data as { name: string }[];-- if (!tableNames.some((r) => r.name === "events_full")) {- // Retry if the table does not exist as this may mean migrations are still pending- if (attempts > 0) {- logger.info(- `ClickHouse events_full table does not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);- });- }-- return {- valid: false,- invalidReason: "ClickHouse events_full table does not exist",- };- }-- // Validate prerequisites (sorted tables, events_backfill, backfill_chunks)- const prereqResult = await this.validatePrerequisites();- if (!prereqResult.valid) {- return {- valid: false,- invalidReason: prereqResult.reason,- };- }-- logger.info("[Backfill Events] All prerequisites validated successfully");-- return { valid: true, invalidReason: undefined };- }-- // ============================================================================- // Main Run Loop- // ============================================================================-- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- const migrationArgs = args as MigrationArgs;-- // Parse config from args- const config: MigrationState["config"] = {- concurrency: migrationArgs.concurrency ?? DEFAULT_CONFIG.concurrency,- pollIntervalMs:- migrationArgs.pollIntervalMs ?? DEFAULT_CONFIG.pollIntervalMs,- maxRetries: migrationArgs.maxRetries ?? DEFAULT_CONFIG.maxRetries,- };-- logger.info(- `[Backfill Events] Starting historic event backfill with config: ${JSON.stringify(config)}`,- );-- // Load or initialize state- let state = await this.loadState();- state.config = config;-- // Phase 1: Load chunks from backfill_chunks table (one-time)- if (state.phase === "init" || state.phase === "loading_chunks") {- if (!state.chunksLoaded) {- state.phase = "loading_chunks";- await this.updateState(state);-- state.todos = await this.loadChunksFromClickhouse();- state.chunksLoaded = true;- state.phase = "backfill";- await this.updateState(state);- }- }-- // Phase 2: Recover any in-progress queries from previous run- // Returns queries that are still running on ClickHouse so we can track them- const stillRunningTodos = await this.recoverInProgressTodos(state);-- // Phase 2.5: Reset failed chunks to pending if --retry-failed flag is set- if (migrationArgs.retryFailed) {- state = await this.loadState();- const failedChunks = state.todos.filter((t) => t.status === "failed");- if (failedChunks.length > 0) {- logger.info(- `[Backfill Events] Resetting ${failedChunks.length} failed chunks to pending`,- );- for (const todo of state.todos) {- if (todo.status === "failed") {- todo.status = "pending";- todo.error = undefined;- todo.retryCount = 0;- }- }- await this.updateState(state);- }- }-- // Phase 3: Execute chunks with concurrency- const manager = new ConcurrentQueryManager<ChunkTodo>();-- const scheduleNext = async (): Promise<void> => {- if (this.isAborted) return;-- state = await this.loadState();- const pendingTodos = state.todos.filter((t) => t.status === "pending");-- if (pendingTodos.length === 0 && manager.activeCount === 0) {- manager.stopPolling();- state.phase = "completed";- await this.updateState(state);- logger.info("[Backfill Events] All chunks completed!");- return;- }-- if (manager.activeCount >= config.concurrency!) return; // At capacity-- const nextTodo = pendingTodos[0];- if (!nextTodo) return;-- // Mark as in_progress- const todoIndex = state.todos.findIndex((t) => t.id === nextTodo.id);- if (todoIndex === -1) return;-- state.todos[todoIndex].status = "in_progress";- state.todos[todoIndex].queryId = generateQueryId(nextTodo.id);- state.todos[todoIndex].startedAt = new Date().toISOString();- state.activeQueries.push(state.todos[todoIndex].queryId!);- await this.updateState(state);-- // Fire the query- try {- const query = this.buildQuery(state.todos[todoIndex]);- await this.fireQuery(- query,- state.todos[todoIndex].queryId!,- state.todos[todoIndex].retryCount || 0,- );- manager.addQuery(- state.todos[todoIndex],- state.todos[todoIndex].queryId!,- );- logger.info(- `[Backfill Events] Started chunk ${nextTodo.id} with query ${state.todos[todoIndex].queryId}`,- );- } catch (err) {- logger.error(- `[Backfill Events] Failed to start query for ${nextTodo.id}`,- err,- );- state.todos[todoIndex].status = "pending"; // Will retry on next scheduleNext- state.todos[todoIndex].queryId = undefined;- state.activeQueries = state.activeQueries.filter(- (q) => q !== state.todos[todoIndex].queryId,- );- await this.updateState(state);- }- };-- const onComplete = async (- todo: ChunkTodo,- success: boolean,- error?: string,- ): Promise<void> => {- state = await this.loadState();- const todoIndex = state.todos.findIndex((t) => t.id === todo.id);- if (todoIndex === -1) return;-- // Remove from activeQueries- state.activeQueries = state.activeQueries.filter(- (q) => q !== todo.queryId,- );-- if (success) {- state.todos[todoIndex].status = "completed";- state.todos[todoIndex].completedAt = new Date().toISOString();- const completed = state.todos.filter(- (t) => t.status === "completed",- ).length;- const total = state.todos.length;- logger.info(- `[Backfill Events] Completed chunk ${todo.id} (${completed}/${total})`,- );- } else {- state.todos[todoIndex].retryCount =- (state.todos[todoIndex].retryCount || 0) + 1;- if (state.todos[todoIndex].retryCount >= config.maxRetries!) {- state.todos[todoIndex].status = "failed";- state.todos[todoIndex].error = error;- logger.error(- `[Backfill Events] Chunk ${todo.id} failed permanently: ${error}`,- );- } else {- state.todos[todoIndex].status = "pending"; // Retry- logger.warn(- `[Backfill Events] Chunk ${todo.id} failed, will retry (${state.todos[todoIndex].retryCount}/${config.maxRetries}): ${error}`,- );- }- }- await this.updateState(state);- };-- // Start polling and initial scheduling- manager.startPolling(config.pollIntervalMs!, onComplete, scheduleNext);-- // Add recovered still-running queries to the manager so they count against concurrency- // This prevents scheduling new queries on top of already-running ones after a restart- for (const todo of stillRunningTodos) {- manager.addQuery(todo, todo.queryId!);- logger.info(- `[Backfill Events] Added recovered running query ${todo.queryId} for chunk ${todo.id} to manager`,- );- }-- // Schedule initial batch up to concurrency limit (minus already-running recovered queries)- const slotsAvailable = config.concurrency! - stillRunningTodos.length;- for (let i = 0; i < slotsAvailable; i++) {- await scheduleNext();- }-- // Wait for all queries to complete- while (!this.isAborted) {- state = await this.loadState();- const pending = state.todos.filter(- (t) => t.status === "pending" || t.status === "in_progress",- );- if (pending.length === 0) break;- await sleep(config.pollIntervalMs!);- }-- manager.stopPolling();-- if (this.isAborted) {- logger.info(- `[Backfill Events] Migration aborted. Can be resumed from current state.`,- );- return;- }-- // Check for failed chunks- const failed = state.todos.filter((t) => t.status === "failed");- if (failed.length > 0) {- logger.error(- `[Backfill Events] Migration completed with ${failed.length} failed chunks`,- );- }-- logger.info(- `[Backfill Events] Finished historic event backfill in ${((Date.now() - start) / 1000 / 60).toFixed(2)} minutes`,- );- }-- async abort(): Promise<void> {- logger.info("[Backfill Events] Aborting historic event backfill");- this.isAborted = true;- }-}--// ============================================================================-// CLI Entry Point-// ============================================================================--async function main() {- // Global error handlers for better exit diagnostics- process.on("unhandledRejection", (reason) => {- logger.error(- "[Backfill Events] Unhandled promise rejection - process will exit",- {- reason: reason instanceof Error ? reason.message : String(reason),- stack: reason instanceof Error ? reason.stack : undefined,- },- );- process.exit(1);- });-- process.on("uncaughtException", (error) => {- logger.error(- "[Backfill Events] Uncaught exception - process will exit",- error,- );- process.exit(1);- });-- const args = parseArgs({- options: {- concurrency: { type: "string", short: "c", default: "4" },- pollIntervalMs: { type: "string", short: "p", default: "30000" },- maxRetries: { type: "string", short: "r", default: "3" },- retryFailed: { type: "boolean", short: "f", default: false },- },- });-- const migration = new BackfillEventsHistoric();-- const parsedArgs = {- concurrency: parseInt(args.values.concurrency as string, 10),- pollIntervalMs: parseInt(args.values.pollIntervalMs as string, 10),- maxRetries: parseInt(args.values.maxRetries as string, 10),- retryFailed: args.values.retryFailed as boolean,- };-- const validation = await migration.validate(parsedArgs);-- if (!validation.valid) {- logger.error(`Validation failed: ${validation.invalidReason}`);- process.exit(1);- }-- await migration.run(parsedArgs);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`, error);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts b/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.tsdeleted file mode 100644index 933d9181c8..0000000000--- a/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts+++ /dev/null@@ -1,849 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- clickhouseClient,- commandClickhouse,- logger,- queryClickhouse,-} from "@langfuse/shared/src/server";-import { prisma } from "@langfuse/shared/src/db";-import { env } from "../env";-import { parseArgs } from "node:util";-import {- BaseChunkTodo,- ConcurrentQueryManager,- generateQueryId,-} from "./backfillEventsHistoric";--import {- getQueryError,- pollQueryStatus,- sleep,-} from "@langfuse/shared/src/server";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table-const backgroundMigrationId = "d08146bd-3841-4ed3-a42c-5f43ff94b14e";--// ============================================================================-// Types-// ============================================================================--interface ChunkTodo extends BaseChunkTodo {- partId: string; // Unique part identifier from ClickHouse-}--interface MigrationArgs {- concurrency?: number; // Default: 4- pollIntervalMs?: number; // Default: 30_000- maxRetries?: number; // Default: 3- retryFailed?: boolean; // Reset failed chunks to pending-}--interface MigrationState {- phase: "init" | "loading_chunks" | "backfill" | "completed";- chunksLoaded: boolean; // Whether chunks have been loaded from the parts table- todos: ChunkTodo[];- activeQueries: string[]; // Currently running query IDs- config: MigrationArgs;-}--const DEFAULT_CONFIG: MigrationState["config"] = {- concurrency: 4,- pollIntervalMs: 30_000,- maxRetries: 3,- retryFailed: false,-};--// ============================================================================-// Migration Class-// ============================================================================--export default class BackfillEventsHistoricFromParts implements IBackgroundMigration {- private isAborted = false;-- // ============================================================================- // State Management- // ============================================================================-- private async loadState(): Promise<MigrationState> {- const migration = await prisma.backgroundMigration.findUnique({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const defaultState: MigrationState = {- phase: "init",- chunksLoaded: false,- todos: [],- activeQueries: [],- config: { ...DEFAULT_CONFIG },- };-- if (!migration || !migration.state) {- return defaultState;- }-- const state = migration.state as Partial<MigrationState>;-- return {- phase: state.phase ?? defaultState.phase,- chunksLoaded: state.chunksLoaded ?? defaultState.chunksLoaded,- todos: state.todos ?? defaultState.todos,- activeQueries: state.activeQueries ?? defaultState.activeQueries,- config: {- ...DEFAULT_CONFIG,- ...state.config,- },- };- }-- private async updateState(state: MigrationState): Promise<void> {- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: state as any },- });- }-- // ============================================================================- // Prerequisite Validation- // ============================================================================-- private async validatePrerequisites(): Promise<{- valid: boolean;- reason?: string;- }> {- const requiredTables = [- "observations_pid_tid_sorting",- "traces_pid_tid_sorting",- "events_full",- "events_core",- ];-- for (const table of requiredTables) {- try {- const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM ${table} LIMIT 1`,- tags: {- feature: "background-migration",- operation: "validatePrerequisites",- table,- },- });- if (!result.length) {- return { valid: false, reason: `${table} table does not exist` };- }- } catch {- return {- valid: false,- reason: `${table} table does not exist or is not accessible`,- };- }- }-- return { valid: true };- }-- // ============================================================================- // Load Parts from ClickHouse- // ============================================================================-- private async loadPartsFromClickhouse(): Promise<ChunkTodo[]> {- logger.info("[Backfill Events] Loading parts from system.parts table");-- const parts = await queryClickhouse<{- partition_id: string;- name: string;- }>({- query: `- SELECT partition_id, name- FROM system.parts- WHERE database = 'default'- AND table = 'observations_pid_tid_sorting'- AND active = 1- AND partition_id IN ('202602', '202601')- ORDER BY partition_id DESC- `,- tags: {- feature: "background-migration",- operation: "loadPartsFromClickhouse",- },- });-- logger.info(- `[Backfill Events] Loaded ${parts.length} parts from clickhouse system table`,- );-- return parts.map((part) => ({- id: part.name,- partId: part.name,- partition: part.partition_id,- status: "pending" as const,- }));- }-- // ============================================================================- // Part Verification- // ============================================================================-- private async verifyPartStillActive(partId: string): Promise<boolean> {- const result = await queryClickhouse<{ count: string }>({- query: `- SELECT count() as count- FROM system.parts- WHERE database = 'default'- AND table = 'observations_pid_tid_sorting'- AND name = '${partId}'- AND active = 1- `,- tags: {- feature: "background-migration",- operation: "verifyPartStillActive",- },- });-- return result.length > 0 && parseInt(result[0].count, 10) > 0;- }-- private async getActivePartIds(): Promise<Set<string>> {- const parts = await queryClickhouse<{ name: string }>({- query: `- SELECT name- FROM system.parts- WHERE database = 'default'- AND table = 'observations_pid_tid_sorting'- AND active = 1- `,- tags: {- feature: "background-migration",- operation: "getActivePartIds",- },- });- return new Set(parts.map((p) => p.name));- }-- // ============================================================================- // Recovery Logic- // ============================================================================-- /**- * Recovers in-progress todos from a previous run.- * Returns an array of todos that are still running and should be added to the query manager.- */- private async recoverInProgressTodos(- state: MigrationState,- ): Promise<ChunkTodo[]> {- const inProgress = state.todos.filter(- (t) => t.status === "in_progress" && t.queryId,- );-- if (inProgress.length === 0) {- return [];- }-- logger.info(- `[Backfill Events] Recovering ${inProgress.length} in-progress part`,- );-- const stillRunning: ChunkTodo[] = [];-- for (const todo of inProgress) {- const status = await pollQueryStatus(todo.queryId!);-- if (status === "completed") {- todo.status = "completed";- todo.completedAt = new Date().toISOString();- logger.info(- `[Backfill Events] Recovered part ${todo.partId} as completed`,- );- } else if (status === "failed") {- todo.status = "pending"; // Will retry- todo.retryCount = (todo.retryCount || 0) + 1;- const error = await getQueryError(todo.queryId!);- logger.warn(- `[Backfill Events] Recovered part ${todo.partId} as failed, will retry: ${error}`,- );- } else if (status === "running") {- // Query is still running on ClickHouse - track it in the manager- logger.info(- `[Backfill Events] Recovered part ${todo.partId} as still running (query ${todo.queryId}), will continue tracking`,- );- stillRunning.push(todo);- } else {- // not_found - query was lost- todo.status = "pending";- logger.warn(- `[Backfill Events] Recovered part ${todo.partId} as not_found, resetting to pending`,- );- }- }-- await this.updateState(state);- return stillRunning;- }-- // ============================================================================- // Query Building- // ============================================================================-- private buildQuery(todo: ChunkTodo): string {- return `- INSERT INTO events_full (- project_id, trace_id, span_id, parent_span_id, start_time, end_time,- name, type, environment, version, release, tags, public, bookmarked,- trace_name, user_id, session_id, 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, usage_pricing_tier_id, usage_pricing_tier_name,- tool_definitions, tool_calls, tool_call_names,- input, output, metadata_names, metadata_values, source,- blob_storage_file_path, event_bytes, created_at, updated_at, event_ts, is_deleted- )- SELECT- o.project_id,- o.trace_id,- o.id AS span_id,- if(o.id = o.trace_id, NULL, coalesce(o.parent_observation_id, concat('t-', o.trace_id))) AS parent_span_id,- o.start_time AS start_time,- o.end_time,- o.name,- o.type,- o.environment,- coalesce(o.version, t.version) as version,- coalesce(t.release, '') as release,- t.tags as tags,- t.public as public,- t.bookmarked as bookmarked,- coalesce(t.name, '') AS trace_name,- coalesce(t.user_id, '') AS user_id,- coalesce(t.session_id, '') AS session_id,- o.level,- coalesce(o.status_message, '') AS status_message,- o.completion_start_time,- o.prompt_id,- o.prompt_name,- o.prompt_version,- o.internal_model_id AS model_id,- o.provided_model_name,- coalesce(o.model_parameters, '{}') AS model_parameters,- o.provided_usage_details,- o.usage_details,- o.provided_cost_details,- o.cost_details,- o.usage_pricing_tier_id,- o.usage_pricing_tier_name,- o.tool_definitions,- o.tool_calls,- o.tool_call_names,- coalesce(o.input, '') AS input,- coalesce(o.output, '') AS output,- mapKeys(o.metadata) AS metadata_names,- mapValues(o.metadata) AS metadata_values,- multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,- '' AS blob_storage_file_path,- 0 AS event_bytes,- o.created_at,- o.updated_at,- o.event_ts,- o.is_deleted- FROM observations_pid_tid_sorting o- LEFT ANY JOIN (select * from traces_pid_tid_sorting where _partition_id = '${todo.partition}') t- ON o.project_id = t.project_id AND o.trace_id = t.id- WHERE o._partition_id = '${todo.partition}'- AND o._part = '${todo.partId}'- AND o.start_time >= toDateTime64('2026-01-20 00:00:00', 3)- AND o.start_time < toDateTime64('2026-02-22 00:00:00', 3)- SETTINGS- join_algorithm = 'full_sorting_merge',- type_json_skip_duplicated_paths = 1- `;- }-- // ============================================================================- // Fire Query (with tracking)- // ============================================================================-- private async fireQuery(- query: string,- queryId: string,- retryCount: number = 0,- ): Promise<void> {- logger.info(`[Backfill Events] Firing query ${queryId}`);-- // Create AbortController to abort HTTP connection after query starts on server.- // This follows ClickHouse best practices for long-running queries:- // https://github.com/ClickHouse/clickhouse-js/blob/main/examples/long_running_queries_timeouts.ts- const abortController = new AbortController();-- // Apply memory-reducing settings on retries- const retrySettings =- retryCount > 1- ? {- max_threads: 1,- max_insert_threads: "1",- max_block_size: "2048",- }- : retryCount > 0- ? {- min_insert_block_size_rows: "5485450",- min_insert_block_size_bytes: "2Gi",- max_threads: 8,- max_block_size: "4096",- }- : retryCount === 0- ? {- min_insert_block_size_rows: "5485450",- min_insert_block_size_bytes: "2Gi",- max_threads: 32,- max_block_size: "8192",- }- : {};-- if (retryCount > 0) {- logger.info(- `[Backfill Events] Applying retry settings for query ${queryId}: ${JSON.stringify(retrySettings)} (retry ${retryCount})`,- );- }-- // Fire the query with abort signal. The query will continue on the server- // even after we abort the HTTP connection.- const queryPromise = commandClickhouse({- query,- tags: {- feature: "background-migration",- operation: "fireQuery",- queryId,- },- // clickhouseConfigs: {- // request_timeout: timeoutMs,- // },- clickhouseSettings: {- // send_progress_in_http_headers: 1,- // http_headers_progress_interval_ms: "30000",- ...retrySettings,- },- abortSignal: abortController.signal,- });-- // Wait a short time to ensure query is registered- await sleep(5000);-- // Verify query is running on server- const status = await pollQueryStatus(queryId);- if (status === "not_found") {- // Query may have completed very quickly or failed to start.- // Wait longer to allow query_log to flush (default flush interval is ~7.5s,- // plus time for cluster replication across shards).- await sleep(30000);- const retryStatus = await pollQueryStatus(queryId);- if (retryStatus === "not_found") {- throw new Error(`Query ${queryId} failed to start on server`);- }- }-- // Abort the HTTP connection now that the query is confirmed running on the server.- // This prevents "Broken pipe" errors from the connection timing out.- // The query continues executing on ClickHouse - we track completion via polling.- logger.info(- `[Backfill Events] Query ${queryId} confirmed running, aborting HTTP connection`,- );- abortController.abort();-- // Handle the expected abort error- queryPromise.catch((err) => {- // Abort errors are expected - log at debug level- if (err?.name === "AbortError" || err?.message?.includes("aborted")) {- logger.debug(- `[Backfill Events] Query ${queryId} HTTP connection aborted as expected`,- );- } else {- logger.info(- `[Backfill Events] Query ${queryId} promise rejected: ${err?.message}`,- err,- );- }- });- }-- // ============================================================================- // Validation- // ============================================================================-- async validate(- args: Record<string, unknown>,- attempts = 5,- ): Promise<{ valid: boolean; invalidReason: string | undefined }> {- // Ensure the background migration record exists- // TODO: Remove for golive- await prisma.backgroundMigration.upsert({- where: { id: backgroundMigrationId },- create: {- id: backgroundMigrationId,- name: "20251211_backfill_events_historic_from_parts",- script: "backfillEventsHistoricFromParts",- args: {},- state: {},- },- update: {},- });-- // Check if ClickHouse credentials are configured- if (- !env.CLICKHOUSE_URL ||- !env.CLICKHOUSE_USER ||- !env.CLICKHOUSE_PASSWORD- ) {- return {- valid: false,- invalidReason:- "ClickHouse credentials must be configured to perform migration",- };- }-- // Check if ClickHouse events_full table exists- const tables = await clickhouseClient().query({- query: "SHOW TABLES",- });- const tableNames = (await tables.json()).data as { name: string }[];-- if (!tableNames.some((r) => r.name === "events_full")) {- // Retry if the table does not exist as this may mean migrations are still pending- if (attempts > 0) {- logger.info(- `ClickHouse events_full table does not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);- });- }-- return {- valid: false,- invalidReason: "ClickHouse events_full table does not exist",- };- }-- // Validate prerequisites (sorted tables)- const prereqResult = await this.validatePrerequisites();- if (!prereqResult.valid) {- return {- valid: false,- invalidReason: prereqResult.reason,- };- }-- logger.info("[Backfill Events] All prerequisites validated successfully");-- return { valid: true, invalidReason: undefined };- }-- // ============================================================================- // Main Run Loop- // ============================================================================-- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- const migrationArgs = args as MigrationArgs;-- // Parse config from args- const config: MigrationState["config"] = {- concurrency: migrationArgs.concurrency ?? DEFAULT_CONFIG.concurrency,- pollIntervalMs:- migrationArgs.pollIntervalMs ?? DEFAULT_CONFIG.pollIntervalMs,- maxRetries: migrationArgs.maxRetries ?? DEFAULT_CONFIG.maxRetries,- retryFailed: migrationArgs.retryFailed ?? DEFAULT_CONFIG.retryFailed,- };-- logger.info(- `[Backfill Events] Starting historic event backfill with config: ${JSON.stringify(config)}`,- );-- // Load or initialize state- let state = await this.loadState();- state.config = config;-- // Phase 1: Load parts from system.parts table (one-time)- if (state.phase === "init" || state.phase === "loading_chunks") {- if (!state.chunksLoaded) {- state.phase = "loading_chunks";- await this.updateState(state);-- state.todos = await this.loadPartsFromClickhouse();- state.chunksLoaded = true;- state.phase = "backfill";- await this.updateState(state);- }- }-- // Phase 2: Recover any in-progress queries from previous run- // Returns queries that are still running on ClickHouse so we can track them- const stillRunningTodos = await this.recoverInProgressTodos(state);-- // Phase 2.5: Reset failed chunks to pending if --retry-failed flag is set- if (config.retryFailed) {- state = await this.loadState();- const failedChunks = state.todos.filter((t) => t.status === "failed");- if (failedChunks.length > 0) {- logger.info(- `[Backfill Events] Resetting ${failedChunks.length} failed chunks to pending`,- );- for (const todo of state.todos) {- if (todo.status === "failed") {- todo.status = "pending";- todo.error = undefined;- todo.retryCount = 0;- }- }- await this.updateState(state);- }- }-- // Phase 3: Execute chunks with concurrency- const manager = new ConcurrentQueryManager<ChunkTodo>();-- const scheduleNext = async (): Promise<void> => {- if (this.isAborted) return;-- state = await this.loadState();- const pendingTodos = state.todos.filter((t) => t.status === "pending");-- if (pendingTodos.length === 0 && manager.activeCount === 0) {- manager.stopPolling();- state.phase = "completed";- await this.updateState(state);- logger.info("[Backfill Events] All chunks completed!");- return;- }-- if (manager.activeCount >= config.concurrency!) return; // At capacity-- const nextTodo = pendingTodos[0];- if (!nextTodo) return;-- // Mark as in_progress- const todoIndex = state.todos.findIndex(- (t) => t.partId === nextTodo.partId,- );- if (todoIndex === -1) return;-- state.todos[todoIndex].status = "in_progress";- state.todos[todoIndex].queryId = generateQueryId(nextTodo.partId);- state.todos[todoIndex].startedAt = new Date().toISOString();- state.activeQueries.push(state.todos[todoIndex].queryId!);- await this.updateState(state);-- // Fire the query- try {- const query = this.buildQuery(state.todos[todoIndex]);- await this.fireQuery(- query,- state.todos[todoIndex].queryId!,- state.todos[todoIndex].retryCount || 0,- );- manager.addQuery(- state.todos[todoIndex],- state.todos[todoIndex].queryId!,- );- logger.info(- `[Backfill Events] Started chunk ${nextTodo.partId} with query ${state.todos[todoIndex].queryId}`,- );- } catch (err) {- logger.error(- `[Backfill Events] Failed to start query for ${nextTodo.partId}`,- err,- );- state.todos[todoIndex].status = "pending"; // Will retry on next scheduleNext- state.activeQueries = state.activeQueries.filter(- (q) => q !== state.todos[todoIndex].queryId,- );- state.todos[todoIndex].queryId = undefined;- await this.updateState(state);- }- };-- const onComplete = async (- todo: ChunkTodo,- success: boolean,- error?: string,- ): Promise<void> => {- state = await this.loadState();- const todoIndex = state.todos.findIndex((t) => t.partId === todo.partId);- if (todoIndex === -1) return;-- // Remove from activeQueries- state.activeQueries = state.activeQueries.filter(- (q) => q !== todo.queryId,- );-- if (success) {- // Verify the part still exists before marking as completed- const partStillActive = await this.verifyPartStillActive(todo.partId);-- if (!partStillActive) {- logger.error(- `[Backfill Events] CRITICAL: Part ${todo.partId} no longer exists after processing! ` +- `Data may be incomplete. Aborting migration.`,- );- state.todos[todoIndex].status = "failed";- state.todos[todoIndex].error =- "Part no longer active after processing - possible data loss";- await this.updateState(state);- this.isAborted = true;- return;- }-- state.todos[todoIndex].status = "completed";- state.todos[todoIndex].completedAt = new Date().toISOString();- const completed = state.todos.filter(- (t) => t.status === "completed",- ).length;- const total = state.todos.length;- logger.info(- `[Backfill Events] Completed part ${todo.partId} (${completed}/${total})`,- );- } else {- state.todos[todoIndex].retryCount =- (state.todos[todoIndex].retryCount || 0) + 1;- if (state.todos[todoIndex].retryCount >= config.maxRetries!) {- state.todos[todoIndex].status = "failed";- state.todos[todoIndex].error = error;- logger.error(- `[Backfill Events] Part ${todo.partId} failed permanently: ${error}`,- );- } else {- state.todos[todoIndex].status = "pending"; // Retry- logger.warn(- `[Backfill Events] Part ${todo.partId} failed, will retry (${state.todos[todoIndex].retryCount}/${config.maxRetries}): ${error}`,- );- }- }- await this.updateState(state);- };-- // Start polling and initial scheduling- manager.startPolling(config.pollIntervalMs!, onComplete, scheduleNext);-- // Add recovered still-running queries to the manager so they count against concurrency- // This prevents scheduling new queries on top of already-running ones after a restart- for (const todo of stillRunningTodos) {- manager.addQuery(todo, todo.queryId!);- logger.info(- `[Backfill Events] Added recovered running query ${todo.queryId} for part ${todo.partId} to manager`,- );- }-- // Schedule initial batch up to concurrency limit (minus already-running recovered queries)- const slotsAvailable = config.concurrency! - stillRunningTodos.length;- for (let i = 0; i < slotsAvailable; i++) {- await scheduleNext();- }-- // Wait for all queries to complete- while (!this.isAborted) {- state = await this.loadState();- const pending = state.todos.filter(- (t) => t.status === "pending" || t.status === "in_progress",- );- if (pending.length === 0) break;- await sleep(config.pollIntervalMs!);- }-- manager.stopPolling();-- if (this.isAborted) {- logger.info(- `[Backfill Events] Migration aborted. Can be resumed from current state.`,- );- return;- }-- // Check for failed chunks- const failed = state.todos.filter((t) => t.status === "failed");- if (failed.length > 0) {- logger.error(- `[Backfill Events] Migration completed with ${failed.length} failed chunks`,- );- }-- // Final verification: ensure all processed parts still exist- const completedTodos = state.todos.filter((t) => t.status === "completed");- if (completedTodos.length > 0) {- logger.info(- `[Backfill Events] Running final verification for ${completedTodos.length} completed parts...`,- );- const activePartIds = await this.getActivePartIds();- const missingParts = completedTodos.filter(- (t) => !activePartIds.has(t.partId),- );-- if (missingParts.length > 0) {- logger.error(- `[Backfill Events] CRITICAL: ${missingParts.length} parts no longer exist after migration! ` +- `Missing parts: ${missingParts- .slice(0, 10)- .map((p) => p.partId)- .join(", ")}` +- `${missingParts.length > 10 ? ` (and ${missingParts.length - 10} more)` : ""}`,- );- throw new Error(- `Migration completed but ${missingParts.length} parts are no longer active - data integrity compromised`,- );- }- logger.info(- `[Backfill Events] Final verification passed - all ${completedTodos.length} parts still active`,- );- }-- logger.info(- `[Backfill Events] Finished historic event backfill in ${((Date.now() - start) / 1000 / 60).toFixed(2)} minutes`,- );- }-- async abort(): Promise<void> {- logger.info("[Backfill Events] Aborting historic event backfill");- this.isAborted = true;- }-}--// ============================================================================-// CLI Entry Point-// ============================================================================--async function main() {- const args = parseArgs({- options: {- concurrency: { type: "string", short: "c", default: "4" },- pollIntervalMs: { type: "string", short: "p", default: "30000" },- maxRetries: { type: "string", short: "r", default: "3" },- retryFailed: { type: "boolean", short: "f", default: false },- },- });-- const migration = new BackfillEventsHistoricFromParts();-- const parsedArgs = {- concurrency: parseInt(args.values.concurrency as string, 10),- pollIntervalMs: parseInt(args.values.pollIntervalMs as string, 10),- maxRetries: parseInt(args.values.maxRetries as string, 10),- retryFailed: args.values.retryFailed as boolean,- };-- const validation = await migration.validate(parsedArgs);-- if (!validation.valid) {- logger.error(`Validation failed: ${validation.invalidReason}`);- process.exit(1);- }-- await migration.run(parsedArgs);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`, error);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/backfillExperimentsHistoric.ts b/worker/src/backgroundMigrations/backfillExperimentsHistoric.tsdeleted file mode 100644index 50f404dabd..0000000000--- a/worker/src/backgroundMigrations/backfillExperimentsHistoric.ts+++ /dev/null@@ -1,603 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- clickhouseClient,- convertDateToClickhouseDateTime,- logger,- queryClickhouse,-} from "@langfuse/shared/src/server";-import { prisma } from "@langfuse/shared/src/db";-import { env } from "../env";-import {- DatasetRunItem,- SpanRecord,- EnrichedSpan,- TraceProperties,- buildSpanMaps,- findAllChildren,- enrichSpansWithExperiment,- writeEnrichedSpans,-} from "../features/eventPropagation/handleExperimentBackfill";-import { parseArgs } from "node:util";--// Hard-coded migration ID (must match the Prisma migration INSERT)-const backgroundMigrationId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";--// Configuration defaults-const DEFAULT_CHUNK_SIZE = 1_000;-const DEFAULT_BATCH_TIMEOUT_MS = 600_000; // 10 minutes--// ============================================================================-// Interfaces-// ============================================================================--interface CursorPosition {- project_id: string;- dataset_id: string;- dataset_run_id: string;- id: string;-}--interface MigrationState {- cursor: CursorPosition | null;- totalProcessed: number;- totalDRIs: number | null;- lastUpdated: string;-}--interface MigrationArgs {- chunkSize?: string;- batchTimeoutMs?: string;- maxDate?: string;-}--// ============================================================================-// Migration Class-// ============================================================================--export default class BackfillExperimentsHistoric implements IBackgroundMigration {- private isAborted = false;-- // --------------------------------------------------------------------------- // State Management- // ---------------------------------------------------------------------------- private async loadState(): Promise<MigrationState> {- const migration = await prisma.backgroundMigration.findUnique({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const defaultState: MigrationState = {- cursor: null,- totalProcessed: 0,- totalDRIs: null,- lastUpdated: new Date().toISOString(),- };-- if (!migration || !migration.state) {- return defaultState;- }-- const state = migration.state as any;- return {- cursor: state.cursor ?? null,- totalProcessed: state.totalProcessed ?? 0,- totalDRIs: state.totalDRIs ?? null,- lastUpdated: state.lastUpdated ?? new Date().toISOString(),- };- }-- private async updateState(state: MigrationState): Promise<void> {- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: state as any },- });- }-- // --------------------------------------------------------------------------- // DRI Fetching- // ---------------------------------------------------------------------------- private async countTotalDRIs(maxDate: Date): Promise<number> {- const result = await queryClickhouse<{ count: string }>({- query: `SELECT count(*) as count FROM dataset_run_items_rmt WHERE created_at <= {maxDate: DateTime64(3)}`,- params: { maxDate: convertDateToClickhouseDateTime(maxDate) },- tags: {- feature: "background-migration",- operation: "countTotalDRIs",- },- });- return parseInt(result[0]?.count ?? "0", 10);- }-- private async fetchDRIsChunk(- cursor: CursorPosition | null,- chunkSize: number,- maxDate: Date,- ): Promise<DatasetRunItem[]> {- let query: string;-- if (cursor === null) {- // First chunk - no cursor- query = `- 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_version,- dri.dataset_item_expected_output,- dri.dataset_item_metadata,- dri.created_at- FROM dataset_run_items_rmt AS dri- WHERE dri.created_at <= {maxDate: DateTime64(3)}- ORDER BY dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.id- LIMIT 1 BY dri.project_id, dri.trace_id, coalesce(dri.observation_id, '')- LIMIT {chunkSize: UInt32}- `;- } else {- // Subsequent chunks - use cursor- query = `- 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_version,- dri.dataset_item_expected_output,- dri.dataset_item_metadata,- dri.created_at- FROM dataset_run_items_rmt AS dri- WHERE (dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.id) >- ({cursor_project_id: String}, {cursor_dataset_id: String}, {cursor_dataset_run_id: String}, {cursor_id: String})- AND dri.created_at <= {maxDate: DateTime64(3)}- ORDER BY dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.id- LIMIT 1 BY dri.project_id, dri.trace_id, coalesce(dri.observation_id, '')- LIMIT {chunkSize: UInt32}- `;- }-- return queryClickhouse<DatasetRunItem>({- query,- params: cursor- ? {- cursor_project_id: cursor.project_id,- cursor_dataset_id: cursor.dataset_id,- cursor_dataset_run_id: cursor.dataset_run_id,- cursor_id: cursor.id,- chunkSize,- maxDate: convertDateToClickhouseDateTime(maxDate),- }- : { chunkSize, maxDate: convertDateToClickhouseDateTime(maxDate) },- tags: {- feature: "background-migration",- operation: "fetchDRIsChunk",- },- });- }-- // --------------------------------------------------------------------------- // Span Fetching- // ---------------------------------------------------------------------------- private async fetchObservationsForTraces(- projectIds: string[],- traceIds: string[],- ): 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,- o.start_time,- o.end_time,- o.name,- 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,- coalesce(o.status_message, '') AS status_message,- o.completion_start_time,- coalesce(o.prompt_id, '') AS prompt_id,- coalesce(o.prompt_name, '') AS prompt_name,- o.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,- o.usage_details,- o.provided_cost_details,- o.cost_details,- coalesce(o.total_cost, 0) AS total_cost,- o.tool_definitions,- o.tool_calls,- o.tool_call_names,- o.usage_pricing_tier_id,- o.usage_pricing_tier_name,- o.metadata,- multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-backfill-experiments', 'ingestion-api-backfill-experiments') AS source,- [] AS tags,- false AS bookmarked,- false AS public,- '' as trace_name,- '' 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)}- ORDER BY o.event_ts DESC- LIMIT 1 BY o.project_id, o.trace_id, o.id- `;-- return queryClickhouse<SpanRecord>({- query,- params: { projectIds, traceIds },- tags: {- feature: "background-migration",- operation: "fetchObservationsForTraces",- },- });- }-- private async fetchTracesForTraces(- projectIds: string[],- traceIds: string[],- ): 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,- NULL AS end_time,- t.name AS name,- '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,- '' 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,- map() AS tool_definitions,- [] AS tool_calls,- [] AS tool_call_names,- t.metadata,- multiIf(mapContains(t.metadata, 'resourceAttributes'), 'otel-backfill-experiments', 'ingestion-api-backfill-experiments') AS source,- t.tags,- t.bookmarked,- t.public,- t.name as trace_name,- 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)}- ORDER BY t.event_ts DESC- LIMIT 1 BY t.project_id, t.id- `;-- return queryClickhouse<SpanRecord>({- query,- params: { projectIds, traceIds },- tags: {- feature: "background-migration",- operation: "fetchTracesForTraces",- },- });- }-- // --------------------------------------------------------------------------- // Validation- // ---------------------------------------------------------------------------- async validate(- args: Record<string, unknown>,- attempts = 5,- ): Promise<{ valid: boolean; invalidReason: string | undefined }> {- // Ensure the background migration record exists- await prisma.backgroundMigration.upsert({- where: { id: backgroundMigrationId },- create: {- id: backgroundMigrationId,- name: "20251202_backfill_experiments_historic",- script: "backfillExperimentsHistoric",- args: {},- state: {},- },- update: {},- });-- // Check ClickHouse credentials- if (- !env.CLICKHOUSE_URL ||- !env.CLICKHOUSE_USER ||- !env.CLICKHOUSE_PASSWORD- ) {- return {- valid: false,- invalidReason:- "ClickHouse credentials must be configured to perform migration",- };- }-- // Check required tables exist- const tables = await clickhouseClient().query({ query: "SHOW TABLES" });- const tableNames = (await tables.json()).data as { name: string }[];-- const requiredTables = ["events_full", "dataset_run_items_rmt"];-- for (const tableName of requiredTables) {- if (!tableNames.some((r) => r.name === tableName)) {- if (attempts > 0) {- logger.info(- `[Backfill Experiments] Table ${tableName} does not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(- () => resolve(this.validate(args, attempts - 1)),- 10_000,- );- });- }-- return {- valid: false,- invalidReason: `Required ClickHouse table '${tableName}' does not exist`,- };- }- }-- logger.info("[Backfill Experiments] Validation passed, all tables exist");- return { valid: true, invalidReason: undefined };- }-- // --------------------------------------------------------------------------- // Main Run Loop- // ---------------------------------------------------------------------------- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- const migrationArgs = args as MigrationArgs;- const chunkSize = parseInt(- migrationArgs.chunkSize ?? String(DEFAULT_CHUNK_SIZE),- );- const batchTimeoutMs = parseInt(- migrationArgs.batchTimeoutMs ?? String(DEFAULT_BATCH_TIMEOUT_MS),- );- const maxDate = migrationArgs.maxDate- ? new Date(migrationArgs.maxDate)- : new Date(); // Process everything up to now-- logger.info(- `[Backfill Experiments] Starting historic experiment backfill with args: ${JSON.stringify({ chunkSize, batchTimeoutMs })}`,- );-- // Load state- let state = await this.loadState();-- // Get total count on first run- if (state.totalDRIs === null) {- state.totalDRIs = await this.countTotalDRIs(maxDate);- await this.updateState(state);- logger.info(- `[Backfill Experiments] Total DRIs to process: ${state.totalDRIs.toLocaleString()}`,- );- }-- // Main processing loop- while (!this.isAborted) {- // Fetch next chunk- const dris = await this.fetchDRIsChunk(state.cursor, chunkSize, maxDate);-- if (dris.length === 0) {- logger.info(- "[Backfill Experiments] No more DRIs to process. Migration complete!",- );- break;- }-- logger.info(- `[Backfill Experiments] Processing chunk of ${dris.length} DRIs (total processed: ${state.totalProcessed}/${state.totalDRIs ?? "?"})`,- );-- // Extract unique project and trace IDs- const projectIds = [...new Set(dris.map((dri) => dri.project_id))];- const traceIds = [...new Set(dris.map((dri) => dri.trace_id))];-- // Fetch observations and traces- const [observations, traces] = await Promise.all([- this.fetchObservationsForTraces(projectIds, traceIds),- this.fetchTracesForTraces(projectIds, traceIds),- ]);-- logger.info(- `[Backfill Experiments] Fetched ${observations.length} observations and ${traces.length} traces`,- );-- // Build span maps- const allSpans = [...observations, ...traces];- const { spanMap, childMap } = buildSpanMaps(allSpans);-- // Build trace properties map- const tracePropertiesMap = new Map<string, TraceProperties>();- for (const trace of traces) {- tracePropertiesMap.set(trace.trace_id, {- name: trace.name,- userId: trace.user_id,- sessionId: trace.session_id,- version: trace.version,- release: trace.release,- tags: trace.tags,- bookmarked: trace.bookmarked,- public: trace.public,- });- }-- // Process each DRI and collect enriched spans- const allEnrichedSpans: EnrichedSpan[] = [];- const processedSpanIds = new Set<string>();- let skippedCount = 0;-- for (const dri of dris) {- const rootSpanId = dri.observation_id || `t-${dri.trace_id}`;- const rootSpan = spanMap.get(rootSpanId);-- if (!rootSpan) {- logger.warn(- `[Backfill Experiments] Root span ${rootSpanId} not found for DRI ${dri.id}, skipping`,- );- skippedCount++;- continue;- }-- const traceProperties = tracePropertiesMap.get(dri.trace_id);- const childSpans = findAllChildren(rootSpanId, childMap);-- const enrichedSpans = enrichSpansWithExperiment(- rootSpan,- childSpans,- dri,- traceProperties,- );-- allEnrichedSpans.push(...enrichedSpans);-- // Track processed spans- processedSpanIds.add(rootSpan.span_id);- for (const child of childSpans) {- processedSpanIds.add(child.span_id);- }- }-- if (skippedCount > 0) {- logger.warn(- `[Backfill Experiments] Skipped ${skippedCount} DRIs due to missing root spans`,- );- }-- // Write enriched spans to events_full table- if (allEnrichedSpans.length > 0) {- await writeEnrichedSpans(allEnrichedSpans);- logger.info(- `[Backfill Experiments] Wrote ${allEnrichedSpans.length} enriched spans to events_full table`,- );- }-- // Update cursor to last DRI in this chunk- const lastDRI = dris[dris.length - 1];- state.cursor = {- project_id: lastDRI.project_id,- dataset_id: lastDRI.dataset_id,- dataset_run_id: lastDRI.dataset_run_id,- id: lastDRI.id,- };- state.totalProcessed += dris.length;- state.lastUpdated = new Date().toISOString();- await this.updateState(state);- }-- if (this.isAborted) {- logger.info(- `[Backfill Experiments] Migration aborted. Can be resumed from current state.`,- );- return;- }-- logger.info(- `[Backfill Experiments] Finished historic experiment backfill in ${((Date.now() - start) / 1000 / 60).toFixed(2)} minutes. Total processed: ${state.totalProcessed.toLocaleString()}`,- );- }-- async abort(): Promise<void> {- logger.info("[Backfill Experiments] Aborting historic experiment backfill");- this.isAborted = true;- }-}--// ============================================================================-// CLI Support-// ============================================================================--async function main() {- const args = parseArgs({- options: {- chunkSize: {- type: "string",- short: "c",- default: String(DEFAULT_CHUNK_SIZE),- },- batchTimeoutMs: {- type: "string",- short: "t",- default: String(DEFAULT_BATCH_TIMEOUT_MS),- },- maxDate: {- type: "string",- short: "m",- default: undefined,- },- },- });-- const migration = new BackfillExperimentsHistoric();- const validation = await migration.validate(args.values);-- if (!validation.valid) {- logger.error(`Validation failed: ${validation.invalidReason}`);- process.exit(1);- }-- await migration.run(args.values);-}--if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`, error);- process.exit(1);- });-}diff --git a/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts b/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.tsindex 049e5e1b77..d01a61a32f 100644--- a/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts+++ b/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts@@ -12,7 +12,7 @@ import {} from "@langfuse/shared/src/server";import { Job } from "bullmq";import { prisma } from "@langfuse/shared/src/db";-import { env } from "../../env";+import { env, v4WritesToEventsTable } from "../../env";export const handleDataRetentionProcessingJob = async (job: Job) => {const { projectId, retention } = job.data.payload;@@ -94,7 +94,7 @@ export const handleDataRetentionProcessingJob = async (job: Job) => {deleteTracesOlderThanDays(projectId, cutoffDate),deleteObservationsOlderThanDays(projectId, cutoffDate),deleteScoresOlderThanDays(projectId, cutoffDate),- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ v4WritesToEventsTable(env)? deleteEventsOlderThanDays(projectId, cutoffDate): Promise.resolve(),]);diff --git a/worker/src/env.ts b/worker/src/env.tsindex a69a645d13..28d8704412 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -269,7 +269,7 @@ const EnvSchema = z.object({.default("true"),QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED: z.enum(["true", "false"])- .default("false"),+ .default("true"),QUEUE_CONSUMER_NOTIFICATION_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),@@ -440,20 +440,17 @@ const EnvSchema = z.object({.positive().default(7200), // 2 hours to handle worst-case deletions- LANGFUSE_EXPERIMENT_BACKFILL_EXCLUDE_ATTRIBUTES_KEY: z+ // V4 migration flags. See LFE-9778.+ LANGFUSE_MIGRATION_V4_WRITE_MODE: z+ .enum(["legacy", "dual", "events_only"])+ .default("legacy"),+ LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR: z+ .enum(["dual_write", "direct"])+ .default("dual_write"),+ LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN: z.enum(["true", "false"]).default("false"),- // Deprecated. Do not use!- LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT: z- .enum(["true", "false"])- .default("false"),- LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE: z- .enum(["true", "false"])- .default("false"),- LANGFUSE_EXPERIMENT_EARLY_EXIT_EVENT_BATCH_JOB: z- .enum(["true", "false"])- .default("false"),LANGFUSE_EXPERIMENT_EVENT_PROPAGATION_PARTITION_DELAY_MINUTES: z.coerce.number().positive()@@ -484,7 +481,57 @@ const EnvSchema = z.object({LANGFUSE_QUEUE_METRICS_ENABLED: z.enum(["true", "false"]).default("true"),});-export const env: z.infer<typeof EnvSchema> =+type ParsedEnv = z.infer<typeof EnvSchema>;++// V4 migration flag helpers.+export const v4WritesToEventsTable = (envValue: ParsedEnv): boolean =>+ envValue.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy";++export const v4WritesToLegacyTables = (envValue: ParsedEnv): boolean =>+ envValue.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only";++export const v4ForceDirectOtelWrite = (envValue: ParsedEnv): boolean =>+ envValue.LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR === "direct";++export const v4AllowPreviewOptIn = (envValue: ParsedEnv): boolean =>+ envValue.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";++const validateV4Flags = (parsed: ParsedEnv): void => {+ const mode = parsed.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ const otel = parsed.LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR;++ // Hard errors: combinations that would silently lose data.+ if (mode === "legacy" && otel === "direct") {+ throw new Error(+ "Invalid V4 config: LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=direct " ++ "requires LANGFUSE_MIGRATION_V4_WRITE_MODE in {dual, events_only}. " ++ "Direct OTel writes target events_full, which is not read in legacy mode.",+ );+ }+ if (mode === "events_only" && otel === "dual_write") {+ throw new Error(+ "Invalid V4 config: LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write " ++ "is incoherent with LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only " ++ "(would dual-write to legacy tables the deployment otherwise skips).",+ );+ }+ if (mode === "events_only" && !v4AllowPreviewOptIn(parsed)) {+ throw new Error(+ "Invalid V4 config: LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only requires " ++ "LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true. Web reads are gated " ++ "solely on the opt-in flag; without it they target the legacy " ++ "traces/observations tables that events_only mode no longer writes to.",+ );+ }+};++const parseEnv = (): ParsedEnv => {+ const parsed = EnvSchema.parse(removeEmptyEnvVariables(process.env));+ validateV4Flags(parsed);+ return parsed;+};++export const env: ParsedEnv =process.env.DOCKER_BUILD === "1" // eslint-disable-line turbo/no-undeclared-env-vars? (process.env as any)- : EnvSchema.parse(removeEmptyEnvVariables(process.env));+ : parseEnv();diff --git a/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.tsindex a90656f23a..a329be1f42 100644--- a/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts+++ b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts@@ -20,7 +20,7 @@ vi.mock("../../../env", async (importOriginal) => {...original,env: {...original.env,- LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE: "true",+ LANGFUSE_MIGRATION_V4_WRITE_MODE: "dual",},};});diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex b690b5846d..8ebaa183db 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -259,6 +259,7 @@ export const createEvalJobs = async ({try {// Fetch trace data and store it. If observation data is required, we'll make a separate lookup.// Those fields are used rarely, though.+ // eslint-disable-next-line @typescript-eslint/no-deprecatedcachedTrace = await getTraceById({traceId: event.traceId,projectId: event.projectId,@@ -1259,6 +1260,7 @@ export async function extractVariablesFromTracingData({const traceCacheKey = `${projectId}:${traceId}`;let trace = traceCache.get(traceCacheKey);if (!traceCache.has(traceCacheKey)) {+ // eslint-disable-next-line @typescript-eslint/no-deprecatedtrace = await getTraceById({traceId,projectId,diff --git a/worker/src/features/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.tsindex aff61ed6ec..50ccfda607 100644--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts@@ -63,13 +63,6 @@ export const handleEventPropagationJob = async (job.data.id,);- if (env.LANGFUSE_EXPERIMENT_EARLY_EXIT_EVENT_BATCH_JOB === "true") {- logger.info(- "[DUAL WRITE] Early exit for event propagation job due to experiment flag",- );- return;- }-try {// Step 1: Get the last processed partition from Redis and find the next one to processconst lastProcessedPartition = await getLastProcessedPartition();@@ -96,6 +89,7 @@ export const handleEventPropagationJob = async (SELECT DISTINCT partitionFROM system.partsWHERE table = 'observations_batch_staging'+ AND database = currentDatabase()AND active = 1AND toDateTime(partition) < now() - INTERVAL ${env.LANGFUSE_EXPERIMENT_EVENT_PROPAGATION_PARTITION_DELAY_MINUTES} MINUTE${lastProcessedPartition ? `AND partition > {lastProcessedPartition: String}` : ""}diff --git a/worker/src/features/internal-tracing/createInternalEventsWriter.ts b/worker/src/features/internal-tracing/createInternalEventsWriter.tsindex ac0bb914d6..00bd7db6db 100644--- a/worker/src/features/internal-tracing/createInternalEventsWriter.ts+++ b/worker/src/features/internal-tracing/createInternalEventsWriter.ts@@ -8,7 +8,7 @@ import { clickhouseClient, redis } from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { ClickhouseWriter } from "../../services/ClickhouseWriter";import { IngestionService } from "../../services/IngestionService";-import { env } from "../../env";+import { env, v4WritesToEventsTable } from "../../env";let internalTraceIngestionService: IngestionService | undefined;@@ -37,7 +37,7 @@ async function writeInternalEventInputs(params: {),);- if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true") {+ if (v4WritesToEventsTable(env)) {for (const eventRecord of eventRecords) {service.writeEventRecord(eventRecord);}diff --git a/worker/src/features/notifications/commentMentionHandler.ts b/worker/src/features/notifications/commentMentionHandler.tsindex 600ef0c9e4..df0d8eff11 100644--- a/worker/src/features/notifications/commentMentionHandler.ts+++ b/worker/src/features/notifications/commentMentionHandler.ts@@ -29,6 +29,7 @@ async function buildCommentLink(opts: {switch (comment.objectType) {case "OBSERVATION": {+ // eslint-disable-next-line @typescript-eslint/no-deprecatedconst observation = await getObservationById({id: comment.objectId,projectId,diff --git a/worker/src/features/traces/processClickhouseTraceDelete.ts b/worker/src/features/traces/processClickhouseTraceDelete.tsindex 1b57a66975..16104007e6 100644--- a/worker/src/features/traces/processClickhouseTraceDelete.ts+++ b/worker/src/features/traces/processClickhouseTraceDelete.ts@@ -8,7 +8,7 @@ import {removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces,traceException,} from "@langfuse/shared/src/server";-import { env } from "../../env";+import { env, v4WritesToEventsTable } from "../../env";import { prisma } from "@langfuse/shared/src/db";import { chunk } from "lodash";@@ -139,7 +139,7 @@ export const processClickhouseTraceDelete = async (deleteTraces(projectId, traceIds),deleteObservationsByTraceIds(projectId, traceIds),deleteScoresByTraceIds(projectId, traceIds),- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ v4WritesToEventsTable(env)? deleteEventsByTraceIds(projectId, traceIds): Promise.resolve(),]);diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsindex 1a88478d56..0ecd962d69 100644--- a/worker/src/queues/ingestionQueue.ts+++ b/worker/src/queues/ingestionQueue.ts@@ -20,7 +20,7 @@ import {} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";-import { env } from "../env";+import { env, v4WritesToEventsTable } from "../env";import { IngestionService } from "../services/IngestionService";import { ClickhouseWriter, TableName } from "../services/ClickhouseWriter";import { chunk } from "lodash";@@ -268,7 +268,7 @@ export const ingestionQueueProcessorBuilder = (// Use explicit flag from job payload if provided, otherwise fall back to env flagsconst forwardToEventsTable =job.data.payload.data.forwardToEventsTable ??- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true";+ v4WritesToEventsTable(env);await new IngestionService(redis,diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex 01cdc12d49..0d47b5a2da 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -24,7 +24,12 @@ import {applyIngestionMasking,isIngestionMaskingEnabled,} from "@langfuse/shared/src/server/ee/ingestionMasking";-import { env } from "../env";+import {+ env,+ v4ForceDirectOtelWrite,+ v4WritesToEventsTable,+ v4WritesToLegacyTables,+} from "../env";import { IngestionService } from "../services/IngestionService";import { prisma } from "@langfuse/shared/src/db";import { ClickhouseWriter } from "../services/ClickhouseWriter";@@ -365,7 +370,11 @@ export const otelIngestionQueueProcessorBuilder = (ingestionVersion: job.data.payload.ingestionVersion,});- let useDirectEventWrite = headerBasedDirectWrite;+ // Priority 0: deployment-level override.+ // LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=direct forces every batch+ // onto the direct events_full path regardless of SDK headers/scopes.+ const envForcesDirect = v4ForceDirectOtelWrite(env);+ let useDirectEventWrite = envForcesDirect || headerBasedDirectWrite;if (!useDirectEventWrite) {const hasExperimentEnvironment = observations.some((o) => {@@ -386,47 +395,67 @@ export const otelIngestionQueueProcessorBuilder = ();}- const writePath = useDirectEventWrite- ? headerBasedDirectWrite- ? "direct_header"- : "direct_scope"- : "dual";+ let writePath: "dual" | "direct_header" | "direct_env" | "direct_scope";+ if (!useDirectEventWrite) {+ writePath = "dual";+ } else if (headerBasedDirectWrite) {+ writePath = "direct_header";+ } else if (envForcesDirect) {+ writePath = "direct_env";+ } else {+ writePath = "direct_scope";+ }+span?.setAttribute("langfuse.ingestion.otel.write_path", writePath);recordIncrement("langfuse.ingestion.otel.write_path", 1, {path: writePath,});- const shouldForwardToEventsTable =- !useDirectEventWrite &&- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "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.-- // Process observations via mergeAndWrite- const observationWritePromise = Promise.all(- observations.map((observation) =>- ingestionService.mergeAndWrite(- getClickhouseEntityType(observation.type),- auth.scope.projectId,- observation.body.id || "", // id is always defined for observations- new Date(), // Use the current timestamp as event time- [observation],- shouldForwardToEventsTable,+ // V4 events_only mode: skip the legacy traces/observations write paths.+ // The direct events_full write below is the sole destination — env+ // validation already guarantees useDirectEventWrite is true here, so+ // observations and traces don't need the mergeAndWrite / IngestionQueue+ // detour that would otherwise populate the legacy tables.+ const skipLegacyWrites = !v4WritesToLegacyTables(env);++ if (skipLegacyWrites) {+ span?.setAttribute(+ "langfuse.ingestion.otel.skipped_legacy_writes",+ true,+ );+ recordIncrement("langfuse.ingestion.otel.skipped_legacy_writes", 1);+ } else {+ const shouldForwardToEventsTable =+ !useDirectEventWrite && v4WritesToEventsTable(env);++ // 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.++ // Process observations via mergeAndWrite+ const observationWritePromise = Promise.all(+ observations.map((observation) =>+ ingestionService.mergeAndWrite(+ getClickhouseEntityType(observation.type),+ auth.scope.projectId,+ observation.body.id || "", // id is always defined for observations+ new Date(), // Use the current timestamp as event time+ [observation],+ shouldForwardToEventsTable,+ ),),- ),- );+ );- // Process traces and observations concurrently- await Promise.all([- observationWritePromise,- processEventBatch(traces, auth, {- delay: 0,- source: "otel",- forwardToEventsTable: shouldForwardToEventsTable,- }),- ]);+ // Process traces and observations concurrently+ await Promise.all([+ observationWritePromise,+ processEventBatch(traces, auth, {+ delay: 0,+ source: "otel",+ forwardToEventsTable: shouldForwardToEventsTable,+ }),+ ]);+ }// Process events for observation evals and direct event writes// This phase handles two independent concerns:@@ -443,8 +472,7 @@ export const otelIngestionQueueProcessorBuilder = (// Determine what processing is neededconst shouldWriteToEventsTable =- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" &&- useDirectEventWrite;+ v4WritesToEventsTable(env) && useDirectEventWrite;const evalConfigs = await fetchObservationEvalConfigs(projectId).catch((error) => {diff --git a/worker/src/queues/projectDelete.ts b/worker/src/queues/projectDelete.tsindex fea23c43a5..4311e007f9 100644--- a/worker/src/queues/projectDelete.ts+++ b/worker/src/queues/projectDelete.ts@@ -16,7 +16,7 @@ import {} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { Prisma } from "@prisma/client";-import { env } from "../env";+import { env, v4WritesToEventsTable } from "../env";export const projectDeleteProcessor: Processor = async (job: Job<TQueueJobTypes[QueueName.ProjectDelete]>,@@ -66,7 +66,7 @@ export const projectDeleteProcessor: Processor = async (deleteTracesByProjectId(projectId),deleteObservationsByProjectId(projectId),deleteScoresByProjectId(projectId),- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ v4WritesToEventsTable(env)? deleteEventsByProjectId(projectId): Promise.resolve(),]);diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex d23e6350aa..c13c4bf4e8 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -108,7 +108,7 @@ export class ClickhouseWriter {logger.info("ClickhouseWriter shutdown complete.");}- private async flushAll(fullQueue = false) {+ public async flushAll(fullQueue = false) {return instrumentAsync({name: "write-to-clickhouse",diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex 8fd3b61a86..5e6c2d3a9c 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -22,7 +22,6 @@ import waitForExpect from "wait-for-expect";import { ClickhouseWriter, TableName } from "../../ClickhouseWriter";import { IngestionService } from "../../IngestionService";import { ModelUsageUnit, ScoreSourceEnum } from "@langfuse/shared";-import { env } from "../../../env";let projectId = "";const environment = "default";@@ -2924,36 +2923,6 @@ async function getClickhouseRecord<T extends TableName>(format: "JSONEachRow",});- if (- tableName === "traces" &&- env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true"- ) {- query = await clickhouseClient().query({- query: `SELECT- id,- name as name,- user_id as user_id,- metadata as metadata,- release as release,- version as version,- project_id,- environment,- public as public,- bookmarked as bookmarked,- tags,- input as input,- output as output,- session_id as session_id,- 0 as is_deleted,- start_time as timestamp,- created_at,- updated_at,- updated_at as event_ts- FROM traces_all_amt FINAL WHERE project_id = '${projectId}' AND id = '${entityId}'`,- format: "JSONEachRow",- });- }-result = (await query.json())[0];};