🪢 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
perf(clickhouse): shift to events_full and events_core tables (#11836)
Steffen Schmitze71ee7e9810d
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.ymlindex 33eda0d55b..70f9766225 100644--- a/.github/workflows/deploy.yml+++ b/.github/workflows/deploy.yml@@ -80,9 +80,8 @@ jobs:if (context.ref === "refs/heads/main") {return `["staging"]`}- // TODO revert to: `["prod-eu", "prod-us", "prod-hipaa"]`if (context.ref === "refs/heads/production") {- return `["prod-eu", "prod-us"]`+ return `["prod-eu", "prod-us", "prod-hipaa"]`}}return "[]"diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex cd6dabb6ff..d57e862ec7 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -129,10 +129,7 @@ ORDER BY (TTL s3_first_seen_timestamp + INTERVAL 12 HOURSETTINGS ttl_only_drop_parts = 1;--- Create new events table for development setups.--- We expect this to be fully immutable and eventually replace observations.--- See LFE-5394 for ongoing discussion.--- Remove IF NOT EXISTS when moving this to prod migrations.+-- Create original events table for development setups.CREATE TABLE IF NOT EXISTS events(project_id String,@@ -299,6 +296,394 @@ CREATE TABLE IF NOT EXISTS events-- min_bytes_for_wide_part = 0;+-- 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.+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)),++ -- 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_type type TYPE set(50) GRANULARITY 1,+ INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,+ INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,++ -- 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.+ merge_max_block_size_bytes = '64Mi',+ enable_block_number_column = 1,+ enable_block_offset_column = 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.+CREATE TABLE IF NOT EXISTS events_core+(+ 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)),++ -- 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+ 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,+ input_length UInt64 MATERIALIZED lengthUTF8(input),+ output String,+ 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_type type TYPE set(50) GRANULARITY 1,+ INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,+ INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1+)+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+ enable_block_number_column = 1,+ enable_block_offset_column = 1;++-- Materialized view to populate events_core from events_full table+CREATE MATERIALIZED VIEW IF NOT EXISTS events_core_mv TO events_core AS+SELECT+ project_id,+ trace_id,+ span_id,+ parent_span_id,+ start_time,+ end_time,+ name,+ type,+ environment,+ version,+ release,+ trace_name,+ user_id,+ session_id,+ tags,+ level,+ status_message,+ completion_start_time,+ bookmarked,+ public,+ 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,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted+FROM events_full;++CREATE MATERIALIZED VIEW IF NOT EXISTS events_full_mv TO events_full AS+SELECT+ project_id,+ trace_id,+ span_id,+ parent_span_id,+ start_time,+ end_time,+ name,+ type,+ environment,+ version,+ release,+ trace_name,+ user_id,+ session_id,+ tags,+ level,+ status_message,+ completion_start_time,+ bookmarked,+ public,+ 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_raw_values as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted+FROM events;+EOFecho "Populating development tables with sample data..."diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 5cb0bcced4..78550f0c2f 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -284,6 +284,11 @@ const EnvSchema = z.object({.enum(["true", "false"]).default("true"),+ // Legacy events table (transitional deployment)+ LANGFUSE_LEGACY_EVENTS_TABLE_EXISTS: z+ .enum(["true", "false"])+ .default("true"),+// EE LicenseLANGFUSE_EE_LICENSE_KEY: z.string().optional(),diff --git a/packages/shared/src/server/clickhouse/schema.ts b/packages/shared/src/server/clickhouse/schema.tsindex 0db7a142b9..3dd2a34bc1 100644--- a/packages/shared/src/server/clickhouse/schema.ts+++ b/packages/shared/src/server/clickhouse/schema.ts@@ -2,9 +2,14 @@ export const ClickhouseTableNames = {traces: "traces",observations: "observations",scores: "scores",- events: "events",dataset_run_items_rmt: "dataset_run_items_rmt",+ // Virtual table for UI column mappings validation (eventsTableUiColumnDefinitions).+ events_proto: "events_proto",++ // Actual events tables used for dashboard/metrics query joins.+ events_core: "events_core",+// Virtual tables for dashboards// TODO: Check if we can do this more elegantlyscores_numeric: "scores_numeric",diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.tsindex ab9937392b..662eb19c63 100644--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts@@ -224,7 +224,7 @@ export class CategoryOptionsFilter implements Filter {// stringObject filter is used when we want to filter on a key value pair in metadata.// For observations/traces tables: uses Map column (metadata)-// For events table: uses Array columns (metadata_names/metadata_prefixes)+// For events tables (events_core, events_full): uses Array columns (metadata_names/metadata_values)// We can only filter efficiently on the first level of a json obj.export class StringObjectFilter implements Filter {public clickhouseTable: string;@@ -255,15 +255,19 @@ export class StringObjectFilter implements Filter {const varValueName = `stringObjectValueFilter${clickhouseCompliantRandomCharacters()}`;const prefix = this.tablePrefix ? this.tablePrefix + "." : "";- // Events table uses array columns (metadata_names/metadata_prefixes)+ // Events tables use array columns (metadata_names/metadata_values)// Observations/traces tables use Map column (metadata)- const isEventsTable = this.clickhouseTable === "events";+ const isEventsTable = [+ "events_proto",+ "events_core",+ "events_full",+ ].includes(this.clickhouseTable);let query: string;if (isEventsTable) {- // For events table, use array access: metadata_prefixes[indexOf(metadata_names, key)]+ // For events tables, use array access: metadata_values[indexOf(metadata_names, key)]const namesColumn = `${prefix}metadata_names`;- const valuesColumn = `${prefix}metadata_prefixes`;+ const valuesColumn = `${prefix}metadata_values`;const valueAccessor = `${valuesColumn}[indexOf(${namesColumn}, {${varKeyName}: String})]`;switch (this.operator) {diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex ebeb846f54..c180bd149f 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -1,6 +1,45 @@import { OBSERVATIONS_TO_TRACE_INTERVAL } from "../../repositories/constants";import { FilterList, StringFilter } from "./clickhouse-filter";+/**+ * Extract the output column alias from a field expression (unquoted).+ * E.g. "e.span_id as id" → "id", 'e.trace_id as "trace_id"' → "trace_id"+ */+function extractAlias(expr: string): string {+ const asMatch = expr.match(/\bas\s+"?([\w]+)"?\s*$/i);+ if (asMatch) return asMatch[1];+ // No alias: use the expression after the last dot (e.g. "e.input" → "input")+ const dotIdx = expr.lastIndexOf(".");+ return dotIdx >= 0 ? expr.slice(dotIdx + 1) : expr;+}++/**+ * Any query builder that can produce a final query string with parameters.+ */+export interface QueryWithParams {+ buildWithParams(): { query: string; params: Record<string, any> };+}++/**+ * Builder returned by buildEventsFullTableSplitQuery.+ * Wraps CTEQueryBuilder with a simpler interface (no complex generics).+ * Callers can chain additional CTEs, JOINs, SELECTs, and ORDER BY.+ */+export interface SplitQueryBuilder extends QueryWithParams {+ withCTE(+ name: string,+ cteWithSchema: {+ query: string;+ params: Record<string, any>;+ schema?: string[];+ },+ ): SplitQueryBuilder;+ leftJoin(cteName: string, alias: string, onClause: string): SplitQueryBuilder;+ select(...expressions: string[]): SplitQueryBuilder;+ orderBy(clause: string): SplitQueryBuilder;+ orderByColumns(entries: OrderByEntry[]): SplitQueryBuilder;+}+/*** Types for structured ORDER BY API*/@@ -9,7 +48,7 @@ export type OrderByEntry = { column: string; direction: OrderByDirection };/*** Field mapping: each field defined once with its full SELECT expression- * All queries use `FROM events e` with alias, so all fields use `e.` prefix+ * All queries use `FROM events_<type> e` with alias, so all fields use `e.` prefix*/const EVENTS_FIELDS = {// Aggregates@@ -65,9 +104,7 @@ const EVENTS_FIELDS = {// I/O & metadata fieldsinput: "e.input",output: "e.output",- metadata: "mapFromArrays(e.metadata_names, e.metadata_prefixes) as metadata",- metadataDirect: "e.metadata as metadata", // Direct JSON column access for exports-+ metadata: "mapFromArrays(e.metadata_names, e.metadata_values) as metadata",// Trace-level denormalized fieldstags: "e.tags as tags",release: "e.release as release",@@ -131,7 +168,7 @@ const FIELD_SETS = {tools: ["toolDefinitions", "toolCalls", "toolCallNames"],eventTs: ["eventTs"],- // getById field sets (reuse the same fields - all queries use `FROM events e`)+ // getById field sets (reuse the same fields - all queries use `FROM events_<type> e`)byIdBase: ["id","traceId",@@ -246,12 +283,10 @@ const EVENTS_AGGREGATION_FIELDS = {user_id: "argMaxIf(user_id, event_ts, user_id <> '') AS user_id",input: "argMaxIf(input, event_ts, parent_span_id = '') AS input",output: "argMaxIf(output, event_ts, parent_span_id = '') AS output",- input_truncated:- "argMaxIf(input_truncated, event_ts, parent_span_id = '') AS input_truncated",- output_truncated:- "argMaxIf(output_truncated, event_ts, parent_span_id = '') AS output_truncated",+ // Note: events_core/events_full tables don't have input_truncated/output_truncated columns.+ // Truncation is handled by the materialized view for events_core, or by leftUTF8() at query time.metadata:- "argMaxIf(mapFromArrays(e.metadata_names, e.metadata_prefixes), event_ts, parent_span_id = '') AS metadata",+ "argMaxIf(mapFromArrays(e.metadata_names, e.metadata_values), event_ts, parent_span_id = '') AS metadata",created_at: "min(created_at) AS created_at",updated_at: "max(updated_at) AS updated_at",total_cost: "sum(total_cost) AS total_cost",@@ -347,6 +382,19 @@ abstract class AbstractQueryBuilder {return this;}+ /**+ * Add ORDER BY using OrderByEntry array for structured API+ */+ orderByColumns(entries: OrderByEntry[]): this {+ if (!entries.length) {+ return this;+ }++ const columns: string[] = entries.map((e) => `${e.column} ${e.direction}`);+ this.orderByClause = `ORDER BY ${columns.join(", ")}`;+ return this;+ }+/*** Add LIMIT and OFFSET*/@@ -508,14 +556,21 @@ abstract class BaseEventsQueryBuilder<return this;}- // Use the direction of the first column for project_id- const primaryDirection = entries[0].direction;+ // When ordering by start_time, prepend project_id and toStartOfMinute(e.start_time)+ // to match the table PRIMARY KEY: (project_id, toStartOfMinute(start_time), xxHash32(trace_id))+ const startTimeEntry = entries.find((e) =>+ e.column.replace(/"/g, "").endsWith("start_time"),+ );- // Build ORDER BY clause with project_id prepended- const columns = [- `e.project_id ${primaryDirection}`,- ...entries.map((e) => `${e.column} ${e.direction}`),- ];+ const columns: string[] = [];+ if (startTimeEntry) {+ columns.push(+ `e.project_id ${startTimeEntry.direction}`,+ `toStartOfMinute(e.start_time) ${startTimeEntry.direction}`,+ );+ }++ columns.push(...entries.map((e) => `${e.column} ${e.direction}`));this.orderByClause = `ORDER BY ${columns.join(", ")}`;return this;@@ -540,6 +595,15 @@ abstract class BaseEventsQueryBuilder<*/protected abstract buildGroupByClause(): string;+ /**+ * Get the table name to query from.+ * Subclasses can override to implement dynamic table selection.+ * Default: events_core (lightweight table with truncated I/O)+ */+ protected getTableName(): string {+ return "events_core";+ }+/*** Build the final query string*/@@ -555,8 +619,9 @@ abstract class BaseEventsQueryBuilder<// SELECTparts.push(this.buildSelectClause());- // FROM- parts.push("FROM events e");+ // FROM - choose table based on data requirements+ const tableName = this.getTableName();+ parts.push(`FROM ${tableName} e`);// JOINsconst joinSection = this.buildJoinSection();@@ -619,8 +684,6 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<private ioFields: { truncated: boolean; charLimit?: number } | null = null;// Metadata expansion config: null = use truncated (default), string[] = expand specific keys, empty array = expand allprivate metadataExpansionKeys: string[] | null = null;- // Flag to use direct metadata JSON column instead of array-based metadata- private useDirectMetadata: boolean = false;// Raw SELECT expressions for custom columns (e.g., from CTEs)private rawSelectExpressions: string[] = [];@@ -640,36 +703,20 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<}/**- * Select metadata with expanded values for specified keys.- * Expands truncated metadata values by coalescing with metadata_long_values.+ * Select metadata with expanded (non-truncated) values from events_full.*- * @param keys - Keys to expand. Only the specified keys will have their full values returned.+ * @param keys - Keys to expand. Empty array = expand all keys.** @example- * // Expand specific keys only- * builder.selectMetadataExpanded(['transcript', 'transitions'])+ * builder.selectMetadataExpanded(['transcript', 'transitions']) // specific keys+ * builder.selectMetadataExpanded([]) // all keys*/- selectMetadataExpanded(keys: string[]): this {+ selectMetadataExpanded(keys: string[] = []): this {this.metadataExpansionKeys = keys;- // Also ensure metadata is in the select fields (will be replaced in buildSelectClause)this.selectFields.add("metadata");return this;}- /**- * Select metadata using direct JSON column access instead of array-based reconstruction.- * Use this for exports where full metadata values are needed without truncation.- *- * @example- * builder.selectMetadataDirect()- */- selectMetadataDirect(): this {- this.useDirectMetadata = true;- this.selectFields.add("metadataDirect");-- return this;- }-/*** Add raw SELECT expressions for custom columns (e.g., from CTEs).* These are appended after the field set columns.@@ -738,11 +785,10 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<if (this.ioFields) {fieldsToExclude.push("input", "output");}- // Exclude array-based metadata if using direct JSON metadata or expanded metadata+ // Exclude default metadata when specific expansion keys are provided (custom SELECT expression is added below)if (- this.useDirectMetadata ||- (this.metadataExpansionKeys !== null &&- this.metadataExpansionKeys.length > 0)+ this.metadataExpansionKeys !== null &&+ this.metadataExpansionKeys.length > 0) {fieldsToExclude.push("metadata");}@@ -757,10 +803,11 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<});// Add I/O fields if configured+ // Note: needsFullTable() is responsible for choosing events_core/events_full (truncated vs full I/O)if (this.ioFields) {if (this.ioFields.truncated && this.ioFields.charLimit !== undefined) {fieldExpressions.push(- `leftUTF8(input_truncated, ${this.ioFields.charLimit}) as input, leftUTF8(output_truncated, ${this.ioFields.charLimit}) as output`,+ `leftUTF8(input, ${this.ioFields.charLimit}) as input, leftUTF8(output, ${this.ioFields.charLimit}) as output`,);} else {fieldExpressions.push("input, output");@@ -768,27 +815,18 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<}// Add metadata field with expansion if configured+ // Note: needsFullTable() is responsible for choosing events_core/events_full+ // Metadata expansion is handled by querying events_full directly for full values.if (this.metadataExpansionKeys !== null &&this.metadataExpansionKeys.length > 0 &&this.selectFields.has("metadata")) {- // Add keys to params for safe parameterized query- this.params.expandMetadataKeys = this.metadataExpansionKeys;-- fieldExpressions.push(`mapFromArrays(- e.metadata_names,- arrayMap(- (name, prefix, hash) -> if(- has({expandMetadataKeys: Array(String)}, name) AND isNotNull(hash) AND mapContains(e.metadata_long_values, hash),- e.metadata_long_values[hash],- prefix- ),- e.metadata_names,- e.metadata_prefixes,- e.metadata_hashes- )- ) as metadata`);+ // For events_core/events_full, just use mapFromArrays with metadata_values directly+ // The caller should use events_full table if full metadata is needed+ fieldExpressions.push(+ `mapFromArrays(e.metadata_names, e.metadata_values) as metadata`,+ );}// Add raw SELECT expressions (e.g., from CTE joins)@@ -805,6 +843,44 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<protected buildGroupByClause(): string {return "";}++ /**+ * Determine if query needs events_full table (full I/O and metadata).+ * - events_core: truncated I/O and metadata (faster for most queries)+ * - events_full: full I/O and metadata (when full data is needed)+ */+ private needsFullTable(): boolean {+ // Need full I/O? (truncated = false means we need full data)+ const needsFullIO = this.ioFields !== null && !this.ioFields.truncated;++ // Need full metadata? (any expansion requested — specific keys or all)+ const needsFullMetadata =+ this.metadataExpansionKeys !== null && this.selectFields.has("metadata");++ return needsFullIO || needsFullMetadata;+ }++ /**+ * Get the output column aliases for the currently selected fields.+ * Used by buildEventsFullTableSplitQuery to construct explicit column+ * references instead of b.* (which breaks in ClickHouse JOINs when+ * joined CTEs have overlapping column names).+ */+ getSelectedAliases(): string[] {+ return [...this.selectFields].flatMap((fieldKey) => {+ const expr = EVENTS_FIELDS[fieldKey as keyof typeof EVENTS_FIELDS];+ if (!expr) return [];+ return [extractAlias(expr)];+ });+ }++ /**+ * Get table name based on data requirements.+ * Uses events_full when full I/O or metadata expansion is needed.+ */+ protected override getTableName(): string {+ return this.needsFullTable() ? "events_full" : "events_core";+ }}/**@@ -855,10 +931,29 @@ type AliasedColumns<export class EventsAggregationQueryBuilder extends BaseEventsQueryBuilder<typeof EVENTS_AGGREGATION_FIELDS> {+ private truncated: boolean = true;+constructor(options: { projectId: string }) {super(EVENTS_AGGREGATION_FIELDS, options);}+ /**+ * Set whether to use truncated I/O (events_core) or full I/O (events_full).+ * Default is true (truncated).+ */+ withTruncated(truncated: boolean): this {+ this.truncated = truncated;+ return this;+ }++ /**+ * Get table name based on truncated setting.+ * Uses events_full when full I/O is needed (truncated = false).+ */+ protected override getTableName(): string {+ return this.truncated ? "events_core" : "events_full";+ }+/*** Add SELECT fields from predefined aggregation field sets*/@@ -1155,8 +1250,8 @@ export class EventsAggQueryBuilder extends AbstractCTEQueryBuilder {// SELECTparts.push(`SELECT ${this.selectExpression}`);- // FROM- parts.push("FROM events e");+ // FROM - use events_core for reads (lightweight table with truncated I/O)+ parts.push("FROM events_core e");// JOINsconst joinSection = this.buildJoinSection();@@ -1188,3 +1283,95 @@ export class EventsAggQueryBuilder extends AbstractCTEQueryBuilder {return parts.join("\n");}}++/**+ * Build a CTE-based split query: filter/order on events_core, then fetch+ * IO and/or metadata from events_full only for matched rows.+ *+ * Returns a SplitQueryBuilder that callers can chain onto for additional+ * CTEs, JOINs, SELECTs, and ORDER BY.+ *+ * @example+ * buildEventsFullTableSplitQuery({ projectId, baseBuilder, includeIO: true, includeMetadata: true })+ * .withCTE("scores_agg", { ...eventsScoresAggregation({ projectId }), schema: [] })+ * .leftJoin("scores_agg", "s", "ON s.trace_id = b.trace_id AND s.observation_id = b.id")+ * .select("s.scores_avg as scores_avg", "s.score_categories as score_categories")+ * .orderBy("ORDER BY b.start_time DESC");+ */+export function buildEventsFullTableSplitQuery(opts: {+ projectId: string;+ baseBuilder: EventsQueryBuilder;+ includeIO: boolean;+ includeMetadata: boolean;+ externalCTEs?: Array<{+ name: string;+ queryWithParams: { query: string; params: Record<string, any> };+ }>;+}): SplitQueryBuilder {+ const { query: baseQuery, params: baseParams } =+ opts.baseBuilder.buildWithParams();++ // Build IO CTE: fetch full IO/metadata from events_full for matched rows.+ // Join key columns use _io_ prefix to avoid name clashes with base CTE+ // (ClickHouse excludes duplicate column names from b.* in JOINs).+ const ioSelectParts = [+ "e.span_id as _io_id",+ 'e.trace_id as "_io_trace_id"',+ 'e.start_time as "_io_start_time"',+ ];+ if (opts.includeIO) {+ ioSelectParts.push("e.input", "e.output");+ }+ if (opts.includeMetadata) {+ ioSelectParts.push(+ "mapFromArrays(e.metadata_names, e.metadata_values) as metadata",+ );+ }+ const ioQuery = [+ `SELECT ${ioSelectParts.join(", ")}`,+ "FROM events_full e",+ "WHERE e.project_id = {projectId: String}",+ 'AND (e.start_time, e.trace_id, e.span_id) IN (SELECT "start_time", "trace_id", id FROM base)',+ ].join("\n");++ // Compose final query using CTEQueryBuilder+ let cteBuilder = new CTEQueryBuilder();++ // Register external CTEs (referenced inside base query via JOINs)+ for (const cte of opts.externalCTEs ?? []) {+ cteBuilder = cteBuilder.withCTE(cte.name, {+ ...cte.queryWithParams,+ schema: [] as string[],+ });+ }++ // Register base and io CTEs, set up FROM and JOIN+ cteBuilder = cteBuilder+ .withCTE("base", {+ query: baseQuery,+ params: baseParams,+ schema: [] as string[],+ })+ .withCTE("io", {+ query: ioQuery,+ params: { projectId: opts.projectId },+ schema: [] as string[],+ })+ .from("base", "b")+ .leftJoin(+ "io",+ "i",+ 'ON b."start_time" = i."_io_start_time" AND b."trace_id" = i."_io_trace_id" AND b.id = i._io_id',+ );++ // SELECT: explicit base columns (not b.* — ClickHouse excludes columns+ // from b.* that share names with joined CTEs, and b.col produces JSON+ // keys with the table prefix). Use "b.col as col" for clean JSON keys.+ const baseAliases = opts.baseBuilder.getSelectedAliases();+ cteBuilder.select(...baseAliases.map((a) => `b.${a} as ${a}`));+ if (opts.includeIO)+ cteBuilder.select("i.input as input", "i.output as output");+ if (opts.includeMetadata) cteBuilder.select("i.metadata as metadata");++ return cteBuilder as unknown as SplitQueryBuilder;+}diff --git a/packages/shared/src/server/queries/clickhouse-sql/factory.ts b/packages/shared/src/server/queries/clickhouse-sql/factory.tsindex 951338b730..0fa7cfd458 100644--- a/packages/shared/src/server/queries/clickhouse-sql/factory.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/factory.ts@@ -118,10 +118,10 @@ export const createFilterFromFilterState = (tablePrefix: column.queryPrefix,});case "null":- // Events table uses empty string instead of NULL for parent_span_id+ // Events_* table uses empty string instead of NULL for parent_span_idif (frontEndFilter.column === "parentObservationId" &&- column.clickhouseTableName === "events"+ column.clickhouseTableName.startsWith("events")) {const isNull = frontEndFilter.operator === "is null";const fieldWithPrefix = column.queryPrefixdiff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.tsindex 0a880489f2..9d5d941a23 100644--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts@@ -8,6 +8,11 @@ interface EventsTracesAggregationParams {projectId: string;traceIds?: string[];startTimeFrom?: string | null;+ /**+ * Whether to use truncated I/O (events_core) or full I/O (events_full).+ * Default is false (full) for better compatibility.+ */+ truncated?: boolean;}/**@@ -28,6 +33,7 @@ export const eventsTracesAggregation = (.selectFieldSet("all").withTraceIds(params.traceIds).withStartTimeFrom(params.startTimeFrom)+ .withTruncated(params.truncated ?? false).orderByColumns([{ column: "timestamp", direction: "DESC" }]));};diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex a802cf1f15..ffdfb78ec5 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -36,8 +36,10 @@ export {EventsAggQueryBuilder,EventsAggregationQueryBuilder,EventsQueryBuilder,+ buildEventsFullTableSplitQuery,type CTESchema,type CTEWithSchema,+ type SplitQueryBuilder,} from "./clickhouse-sql/event-query-builder";export {eventsScoresAggregation,diff --git a/packages/shared/src/server/queries/public-api-filter-builder.ts b/packages/shared/src/server/queries/public-api-filter-builder.tsindex 187a1e2781..2075b12fdf 100644--- a/packages/shared/src/server/queries/public-api-filter-builder.ts+++ b/packages/shared/src/server/queries/public-api-filter-builder.ts@@ -83,8 +83,8 @@ const TRACES_COLUMN_DEFINITIONS = [* Convenience function: Get just the simple filter mappings for public API*/export function createPublicApiTracesColumnMapping(- tableName: "traces" | "events",- tablePrefix: "t" | "e",+ tableName: "traces",+ tablePrefix: "t",): ApiColumnMapping[] {const timestampColumn = "timestamp";const simpleFilters: ApiColumnMapping[] = [];@@ -128,7 +128,7 @@ export function createPublicApiTracesColumnMapping(* Eliminates duplication between events and observations filter mappings.*/export function createPublicApiObservationsColumnMapping(- tableName: "events" | "observations",+ tableName: "events_proto" | "observations",tablePrefix: "e" | "o",parentFieldName: "parent_span_id" | "parent_observation_id",): ApiColumnMapping[] {diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex f0ad7017b8..176efdabcf 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -98,6 +98,22 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {return s3StorageServiceClient;};+/**+ * Guard against reads from the legacy 'events' table.+ * Reads must use events_core or events_full instead.+ * Matches "FROM events" or "JOIN events" as a standalone table name+ * (not events_core, events_full, or CTE aliases like filtered_events).+ */+const LEGACY_EVENTS_TABLE_PATTERN = /\b(?:from|join)\s+events\b(?!_)/i;++function assertNoLegacyEventsRead(query: string): void {+ if (LEGACY_EVENTS_TABLE_PATTERN.test(query)) {+ throw new Error(+ `Reading from legacy 'events' table is forbidden. Use events_core or events_full. Query: ${query.slice(0, 200)}`,+ );+ }+}+export async function upsertClickhouse<T extends Record<string, unknown>,>(opts: {@@ -211,7 +227,10 @@ export async function* queryClickhouseStream<T>(opts: {tags?: Record<string, string>;preferredClickhouseService?: PreferredClickhouseService;clickhouseSettings?: ClickHouseSettings;+ allowLegacyEventsRead?: boolean;}): AsyncGenerator<T> {+ if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+const tracer = getTracer("clickhouse-query-stream");const span = tracer.startSpan("clickhouse-query-stream", {kind: SpanKind.CLIENT,@@ -349,7 +368,10 @@ export async function queryClickhouse<T>(opts: {tags?: Record<string, string>;preferredClickhouseService?: PreferredClickhouseService;clickhouseSettings?: ClickHouseSettings;+ allowLegacyEventsRead?: boolean;}): Promise<T[]> {+ if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+return await instrumentAsync({ name: "clickhouse-query", spanKind: SpanKind.CLIENT },async (span) => {diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex 5cef146e72..0364fc5a2e 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -722,7 +722,7 @@ export const eventRecordBaseSchema = z.object({export type EventRecordBaseType = z.infer<typeof eventRecordBaseSchema>;export const eventRecordReadSchema = eventRecordBaseSchema.extend({- metadata_prefixes: z.array(z.string()).default([]),+ metadata_values: z.array(z.string()).default([]),metadata_hashes: z.array(z.number().int()).default([]),metadata_long_values: z.record(z.number().int(), z.string()).default({}),total_cost: z.number().nullish(),diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex b04e566cbf..b5128280ef 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -63,11 +63,29 @@ import {EventsQueryBuilder,CTEQueryBuilder,EventsAggQueryBuilder,+ buildEventsFullTableSplitQuery,+ type QueryWithParams,+ OrderByEntry,} from "../queries/clickhouse-sql/event-query-builder";import { type EventsObservationPublic } from "../queries/createGenerationsQuery";import { UiColumnMappings } from "../../tableDefinitions";import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";+/**+ * Attempt to command the legacy events table.+ * Skips if env toggle is off; swallows errors if the table no longer exists.+ */+async function commandLegacyEventsTable(+ opts: Parameters<typeof commandClickhouse>[0],+): Promise<void> {+ if (env.LANGFUSE_LEGACY_EVENTS_TABLE_EXISTS !== "true") return;+ try {+ await commandClickhouse(opts);+ } catch (e) {+ logger.warn("Legacy events table command failed (table may not exist)", e);+ }+}+type ObservationsTableQueryResultWitouhtTraceFields = Omit<ObservationsTableQueryResult,"trace_tags" | "trace_name" | "trace_user_id"@@ -207,12 +225,15 @@ async function enrichObservationsWithTraceFields(*/function extractTimeFilter(filter: FilterList,- tableName: "events" | "traces" = "events",+ tableName: "events_proto" | "traces" = "events_proto",fieldName: "start_time" | "timestamp" = "start_time",): string | null {const timeFilter = filter.find((f) =>- f.clickhouseTable === tableName &&+ // For events tables, match any events_* prefix (events_proto, events_core, events_full)+ (tableName === "events_proto"+ ? f.clickhouseTable.startsWith("events_")+ : f.clickhouseTable === tableName) &&f.field === fieldName &&(f.operator === ">=" || f.operator === ">"),);@@ -226,7 +247,11 @@ function extractTimeFilter(* Column mapping for public API filters on events table (observations)*/const PUBLIC_API_EVENTS_COLUMN_MAPPING: ApiColumnMapping[] =- createPublicApiObservationsColumnMapping("events", "e", "parent_span_id");+ createPublicApiObservationsColumnMapping(+ "events_proto",+ "e",+ "parent_span_id",+ );/*** Column mappings for traces aggregated from events table@@ -627,12 +652,14 @@ export const getTraceByIdFromEventsTable = async ({preferredClickhouseService?: PreferredClickhouseService;}) => {// Build traces CTE using eventsTracesAggregation+ // Pass truncated flag to select events_core (truncated) or events_full (full I/O)const tracesBuilder = eventsTracesAggregation({projectId,traceIds: [traceId],startTimeFrom: fromTimestamp? convertDateToClickhouseDateTime(fromTimestamp): null,+ truncated: renderingProps.truncated,});// Build the final query@@ -668,13 +695,14 @@ export const getTraceByIdFromEventsTable = async ({}// Handle input/output with truncation+ // Note: eventsTracesAggregation above is responsible for choosing events_core/events_fullif (renderingProps.truncated) {queryBuilder.select(- `leftUTF8(t.input_truncated, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input`,+ `leftUTF8(t.input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input`,).select(- `leftUTF8(t.output_truncated, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as output`,+ `leftUTF8(t.output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as output`,);} else {queryBuilder.selectColumns("t.input", "t.output");@@ -774,10 +802,23 @@ type PublicApiObservationsQuery = {expandMetadataKeys?: string[] | null;};-function buildObservationsQueryBase(+/**+ * Build observation query components: an EventsQueryBuilder (with JOINs and filters but+ * without CTEs) and any external CTEs that should be composed at the outer level.+ *+ * This enables CTE-based split queries where external CTEs (e.g. traces) are hoisted+ * to the outer WITH clause rather than embedded in the EventsQueryBuilder.+ */+function buildObservationsQueryComponents(opts: PublicApiObservationsQuery,columnDefinitions: UiColumnMappings = eventsTableNativeUiColumnDefinitions,-): EventsQueryBuilder {+): {+ queryBuilder: EventsQueryBuilder;+ externalCTEs: Array<{+ name: string;+ queryWithParams: { query: string; params: Record<string, any> };+ }>;+} {const { projectId, advancedFilters, ...filterParams } = opts;// Convert and merge simple and advanced filters@@ -797,14 +838,23 @@ function buildObservationsQueryBase(const startTimeFrom = extractTimeFilter(observationsFilter);const appliedFilter = observationsFilter.apply();- // Build query with common CTE, joins, and filters+ // Build external CTEs+ const externalCTEs: Array<{+ name: string;+ queryWithParams: { query: string; params: Record<string, any> };+ }> = [];+ if (hasTraceFilter) {+ externalCTEs.push({+ name: "traces",+ queryWithParams: eventsTracesAggregation({+ projectId,+ startTimeFrom,+ }).buildWithParams(),+ });+ }++ // Build query with joins and filters (no CTEs)const queryBuilder = new EventsQueryBuilder({ projectId })- .when(hasTraceFilter, (b) =>- b.withCTE(- "traces",- eventsTracesAggregation({ projectId, startTimeFrom }).buildWithParams(),- ),- ).when(hasTraceFilter, (b) =>b.leftJoin("traces t",@@ -813,21 +863,40 @@ function buildObservationsQueryBase().where(appliedFilter);+ return { queryBuilder, externalCTEs };+}++function buildObservationsQueryBase(+ opts: PublicApiObservationsQuery,+ columnDefinitions: UiColumnMappings = eventsTableNativeUiColumnDefinitions,+): EventsQueryBuilder {+ const { queryBuilder, externalCTEs } = buildObservationsQueryComponents(+ opts,+ columnDefinitions,+ );+ for (const cte of externalCTEs) {+ queryBuilder.withCTE(cte.name, cte.queryWithParams);+ }return queryBuilder;}+function orderByForObservationsQuery(+ prefix: string = "e",+ span_id: string = "span_id",+): OrderByEntry[] {+ // Order by to cursor ordering.+ // project_id and potentially other prefixes are injected in the query builder when necessary+ return [+ { column: `${prefix}.start_time`, direction: "DESC" as const },+ { column: `xxHash32(${prefix}.trace_id)`, direction: "DESC" as const },+ { column: `${prefix}.${span_id}`, direction: "DESC" as const },+ ];+}+function applyOrderByForObservationsQuery(queryBuilder: EventsQueryBuilder,): EventsQueryBuilder {- return (- queryBuilder- // Order by to match table ordering- .orderByColumns([- { column: "e.start_time", direction: "DESC" },- { column: "xxHash32(e.trace_id)", direction: "DESC" },- { column: "e.span_id", direction: "DESC" },- ])- );+ return queryBuilder.orderByColumns(orderByForObservationsQuery("e"));}function applyOffsetPagination(@@ -862,7 +931,7 @@ function applyCursorPagination(async function getObservationsRowsFromBuilder<T>(projectId: string,- queryBuilder: EventsQueryBuilder,+ queryBuilder: QueryWithParams,operationName: string = "getObservationsFromEventsTableForPublicApi_rows",): Promise<Array<T>> {const { query, params } = queryBuilder.buildWithParams();@@ -967,56 +1036,76 @@ export const getObservationsFromEventsTableForPublicApi = async (* V2 API: Get observations list from events table for public API* Returns partial observations based on requested field groups* Field filtering happens at query time in ClickHouse+ *+ * When IO or expanded metadata is requested, uses a CTE-based split query:+ * - base CTE: filters/orders/limits on events_core (fast, truncated)+ * - io CTE: fetches full IO/metadata from events_full for matched rows only+ * This avoids expensive full-table scans on events_full.*/export const getObservationsV2FromEventsTableForPublicApi = async (opts: PublicApiObservationsQuery & { fields: ObservationFieldGroup[] },): Promise<Array<EventsObservationPublic>> => {const { projectId, expandMetadataKeys } = opts;- // Build query with filters and common CTEs- let queryBuilder = buildObservationsQueryBase(- opts,- eventsTableNativeUiColumnDefinitions,- );-// Determine which field groups to include- // If fields are not specified (null), include "default" groups: core + basicconst requestedFields = opts.fields ?? ["core", "basic"];- // Core fields are always included (required for cursor pagination)- queryBuilder.selectFieldSet("core");+ const needsIO = requestedFields.includes("io");+ const needsExpandedMetadata =+ requestedFields.includes("metadata") &&+ expandMetadataKeys != null &&+ expandMetadataKeys.length > 0;+ const needsIOCTE = needsIO || needsExpandedMetadata;+ // Metadata goes to io CTE when in CTE mode and metadata is requested+ const metadataFromFullTable =+ needsIOCTE && requestedFields.includes("metadata");++ // Shared: build base query with field sets, ordering, pagination+ const { queryBuilder: baseBuilder, externalCTEs } =+ buildObservationsQueryComponents(+ opts,+ eventsTableNativeUiColumnDefinitions,+ );- // Conditionally add other field sets based on requested groups+ baseBuilder.selectFieldSet("core");+ const excludeFromBase = new Set<string>(["core", "io"]);+ if (metadataFromFullTable) excludeFromBase.add("metadata");requestedFields- .filter((fg) => fg !== "core")- .forEach((fieldGroup) => {- queryBuilder.selectFieldSet(fieldGroup);- });+ .filter((fg) => !excludeFromBase.has(fg))+ .forEach((fg) => baseBuilder.selectFieldSet(fg));- // Handle metadata field with optional expansion- if (requestedFields.includes("metadata")) {- if (expandMetadataKeys && expandMetadataKeys.length > 0) {- // Use expanded metadata (coalesces truncated values with full values)- queryBuilder.selectMetadataExpanded(expandMetadataKeys);+ applyOrderByForObservationsQuery(baseBuilder);+ applyCursorPagination(opts, baseBuilder);++ let builder: QueryWithParams;++ if (!needsIOCTE) {+ // Simple path: add CTEs back to the builder and use directly+ for (const cte of externalCTEs) {+ baseBuilder.withCTE(cte.name, cte.queryWithParams);}+ builder = baseBuilder;+ } else {+ builder = buildEventsFullTableSplitQuery({+ projectId,+ baseBuilder,+ includeIO: needsIO,+ includeMetadata: metadataFromFullTable,+ externalCTEs,+ }).orderByColumns(orderByForObservationsQuery("b", "id"));}- queryBuilder = applyCursorPagination(- opts,- applyOrderByForObservationsQuery(queryBuilder),- );-- const observationRecords =+ const records =await getObservationsRowsFromBuilder<ObservationsTableQueryResultWitouhtTraceFields>(projectId,- queryBuilder,+ builder,);return await enrichObservationsWithModelData(- observationRecords,- opts.projectId,+ records,+ projectId,Boolean(opts.parseIoAsJson),- opts.fields, // V2 API: field groups specified, return partial observations+ opts.fields,);};@@ -1100,9 +1189,11 @@ async function getTracesFromEventsTableForPublicApiInternal<T>(// Build traces CTE using eventsTracesAggregation WITHOUT filters// Filters must be applied AFTER aggregation to ensure filters on aggregated// fields (like timestamp or version) are applied correctly+ // Use events_full when I/O is requested (truncated: false), otherwise events_coreconst tracesBuilder = eventsTracesAggregation({projectId,startTimeFrom,+ truncated: !includeIO,});// Build the final query using CTEQueryBuilder@@ -1277,6 +1368,8 @@ type UpdateableEventFields = {* Both spanIds / traceIds are used only when defined and non-empty.* E.g. `{ traceIds: [...] }` will only filter by traceIds, while* `{ spanIds: [...], traceIds: [...] }` will filter by both.+ *+ * Updates both events_full and events_core tables.*/export const updateEvents = async (projectId: string,@@ -1293,27 +1386,32 @@ export const updateEvents = async (// Nothing to updatereturn;}- const query = `- UPDATE events SET ${setClauses.join(", ")}++ const whereClause = `WHERE project_id = {projectId: String}${selector.spanIds ? "AND span_id IN ({spanIds: Array(String)})" : ""}- ${selector.traceIds ? "AND trace_id IN ({traceIds: Array(String)})" : ""}- ${selector.rootOnly === true ? "AND parent_span_id = ''" : ""}- `;- return await commandClickhouse({- query: query,- params: {- projectId,- spanIds: selector.spanIds ?? [],- traceIds: selector.traceIds ?? [],- ...updates,- },- tags: {- type: "event",- kind: "update",- projectId,- },+ ${selector.traceIds ? "AND trace_id IN ({traceIds: Array(String)})" : ""}+ ${selector.rootOnly === true ? "AND parent_span_id = ''" : ""}+ `;++ const params = {+ projectId,+ spanIds: selector.spanIds ?? [],+ traceIds: selector.traceIds ?? [],+ ...updates,+ };++ const updateOpts = (table: string) => ({+ query: `ALTER TABLE ${table} UPDATE ${setClauses.join(", ")} ${whereClause}`,+ params,+ tags: { type: table, kind: "update", projectId },});++ await Promise.all([+ commandClickhouse(updateOpts("events_full")),+ commandClickhouse(updateOpts("events_core")),+ commandLegacyEventsTable(updateOpts("events")),+ ]);};/**@@ -1495,7 +1593,7 @@ export const getEventsGroupedByTraceTags = async (const query = `SELECT DISTINCT arrayJoin(e.tags) as tag- FROM events e+ FROM events_core eWHERE e.project_id = {projectId: String}AND e.is_deleted = 0${appliedEventsFilter.query ? `AND ${appliedEventsFilter.query}` : ""}@@ -1939,6 +2037,7 @@ export const deleteEventsByTraceIds = async (projectId: string,traceIds: string[],) => {+ // Preflight query uses events_core (faster)const preflight = await queryClickhouse<{min_ts: string;max_ts: string;@@ -1949,7 +2048,7 @@ export const deleteEventsByTraceIds = async (min(start_time) - INTERVAL 1 HOUR as min_ts,max(start_time) + INTERVAL 1 HOUR as max_ts,count(*) as cnt- FROM events+ FROM events_coreWHERE project_id = {projectId: String} AND trace_id IN ({traceIds: Array(String)})`,params: { projectId, traceIds },@@ -1972,36 +2071,45 @@ export const deleteEventsByTraceIds = async (return;}- await commandClickhouse({- query: `- DELETE FROM events- WHERE project_id = {projectId: String}- AND trace_id IN ({traceIds: Array(String)})- AND start_time >= {minTs: String}::DateTime64(3)- AND start_time <= {maxTs: String}::DateTime64(3)- `,- params: {- projectId,- traceIds,- minTs: preflight[0].min_ts,- maxTs: preflight[0].max_ts,- },+ const deleteParams = {+ projectId,+ traceIds,+ minTs: preflight[0].min_ts,+ maxTs: preflight[0].max_ts,+ };+ const deleteQuery = (table: string) => `+ DELETE FROM ${table}+ WHERE project_id = {projectId: String}+ AND trace_id IN ({traceIds: Array(String)})+ AND start_time >= {minTs: String}::DateTime64(3)+ AND start_time <= {maxTs: String}::DateTime64(3)+ `;+ const deleteOpts = (table: string) => ({+ query: deleteQuery(table),+ params: deleteParams,clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},tags: {feature: "tracing",- type: "events",+ type: table,kind: "delete",projectId,},});++ // Delete from all tables in parallel+ await Promise.all([+ commandClickhouse(deleteOpts("events_full")),+ commandClickhouse(deleteOpts("events_core")),+ commandLegacyEventsTable(deleteOpts("events")),+ ]);};export const hasAnyEvent = async (projectId: string) => {const query = `SELECT 1- FROM events+ FROM events_coreWHERE project_id = {projectId: String}LIMIT 1`;@@ -2032,29 +2140,23 @@ export const deleteEventsByProjectId = async (return false;}- const query = `- DELETE FROM events- WHERE project_id = {projectId: String};- `;- const tags = {- feature: "tracing",- type: "events",- kind: "delete",- projectId,- };-- await commandClickhouse({- query,+ // Delete from both tables in parallel+ const deleteOpts = (table: string) => ({+ query: `DELETE FROM ${table} WHERE project_id = {projectId: String}`,params: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags,- clickhouseSettings: {- send_logs_level: "trace",- },+ tags: { feature: "tracing", type: table, kind: "delete", projectId },+ clickhouseSettings: { send_logs_level: "trace" as const },});+ await Promise.all([+ commandClickhouse(deleteOpts("events_full")),+ commandClickhouse(deleteOpts("events_core")),+ commandLegacyEventsTable(deleteOpts("events")),+ ]);+return true;};@@ -2074,9 +2176,9 @@ export async function getAgentGraphDataFromEventsTable(params: {e.name as name,e.start_time as start_time,e.end_time as end_time,- mapFromArrays(e.metadata_names, e.metadata_prefixes)['langgraph_node'] AS node,- mapFromArrays(e.metadata_names, e.metadata_prefixes)['langgraph_step'] AS step- FROM events e+ mapFromArrays(e.metadata_names, e.metadata_values)['langgraph_node'] AS node,+ mapFromArrays(e.metadata_names, e.metadata_values)['langgraph_step'] AS step+ FROM events_core eWHEREe.project_id = {projectId: String}AND e.trace_id = {traceId: String}@@ -2112,7 +2214,7 @@ export const hasAnyEventOlderThan = async () => {const query = `SELECT 1- FROM events+ FROM events_coreWHERE project_id = {projectId: String}AND start_time < {cutoffDate: DateTime64(3)}LIMIT 1@@ -2148,13 +2250,12 @@ export const deleteEventsOlderThanDays = async (return false;}- const query = `- DELETE FROM events- WHERE project_id = {projectId: String}- AND start_time < {cutoffDate: DateTime64(3)};- `;- await commandClickhouse({- query,+ const deleteOpts = (table: string) => ({+ query: `+ DELETE FROM ${table}+ WHERE project_id = {projectId: String}+ AND start_time < {cutoffDate: DateTime64(3)}+ `,params: {projectId,cutoffDate: convertDateToClickhouseDateTime(beforeDate),@@ -2162,14 +2263,15 @@ export const deleteEventsOlderThanDays = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: "events",- kind: "delete",- projectId,- },+ tags: { feature: "tracing", type: table, kind: "delete", projectId },});+ await Promise.all([+ commandClickhouse(deleteOpts("events_full")),+ commandClickhouse(deleteOpts("events_core")),+ commandLegacyEventsTable(deleteOpts("events")),+ ]);+return true;};@@ -2199,6 +2301,8 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {const minTimestamp = new Date(opts.minStartTime.getTime() - 1000); // -1 second bufferconst maxTimestamp = new Date(opts.maxStartTime.getTime() + 1000); // +1 second buffer+ // Use events_core for truncated reads (lightweight), events_full for full I/O+ const tableName = truncated ? "events_core" : "events_full";const inputSelect = truncated? `leftUTF8(e.input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input`: `e.input as input`;@@ -2211,8 +2315,8 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {e.span_id as id,${inputSelect},${outputSelect},- mapFromArrays(e.metadata_names, e.metadata_prefixes) as metadata- FROM events e+ mapFromArrays(e.metadata_names, e.metadata_values) as metadata+ FROM ${tableName} eWHERE e.project_id = {projectId: String}AND e.span_id IN {observationIds: Array(String)}AND e.trace_id IN {traceIds: Array(String)}@@ -2268,7 +2372,7 @@ const usersFromEventsTableColumnDefinitions: UiColumnMappings = [{uiTableName: "Timestamp",uiTableId: "timestamp",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."start_time"',},];@@ -2338,7 +2442,7 @@ export const getUsersCountFromEventsTable = async (const query = `SELECT uniq(e.user_id) AS totalCount- FROM events e+ FROM events_core eWHERE e.project_id = {projectId: String}AND e.user_id IS NOT NULLAND e.user_id != ''@@ -2468,7 +2572,7 @@ export const hasAnyUserFromEventsTable = async (// Filter out deleted rowsconst query = `SELECT 1- FROM events+ FROM events_coreWHERE project_id = {projectId: String}AND user_id IS NOT NULLAND user_id != ''@@ -2626,7 +2730,7 @@ export const hasAnySessionFromEventsTable = async (): Promise<boolean> => {const query = `SELECT 1- FROM events+ FROM events_coreWHERE project_id = {projectId: String}AND session_id IS NOT NULLAND session_id != ''diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.tsindex 23dca1d88e..02f07c7e5f 100644--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts@@ -7,50 +7,50 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{uiTableName: "Environment",uiTableId: "environment",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."environment"',},{uiTableName: "Type",uiTableId: "type",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."type"',},{uiTableName: "ID",uiTableId: "id",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."span_id"',},{uiTableName: "Name",uiTableId: "name",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."name"',},{uiTableName: "Trace ID",uiTableId: "traceId",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."trace_id"',},{uiTableName: "Start Time",uiTableId: "startTime",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."start_time"',},{uiTableName: "End Time",uiTableId: "endTime",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."end_time"',},{uiTableName: "Time To First Token (s)",uiTableId: "timeToFirstToken",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"if(isNull(e.completion_start_time), NULL, date_diff('millisecond', e.start_time, e.completion_start_time) / 1000)",// If we use the default of Decimal64(12), we cannot filter for more than ~40min due to an overflow@@ -59,7 +59,7 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{uiTableName: "Latency (s)",uiTableId: "latency",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"if(isNull(e.end_time), NULL, date_diff('millisecond', e.start_time, e.end_time) / 1000)",// If we use the default of Decimal64(12), we cannot filter for more than ~40min due to an overflow@@ -68,65 +68,65 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{uiTableName: "Tokens per second",uiTableId: "tokensPerSecond",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details))) / (date_diff('millisecond', start_time, end_time) / 1000))",},{uiTableName: "Input Cost ($)",uiTableId: "inputCost",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details)))",},{uiTableName: "Output Cost ($)",uiTableId: "outputCost",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details)))",},{uiTableName: "Total Cost ($)",uiTableId: "totalCost",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"if(mapExists((k, v) -> (k = 'total'), cost_details), cost_details['total'], NULL)",},{uiTableName: "Level",uiTableId: "level",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."level"',},{uiTableName: "Status Message",uiTableId: "statusMessage",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."status_message"',},{uiTableName: "Model",uiTableId: "model",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."provided_model_name"',},{uiTableName: "Provided Model Name",uiTableId: "providedModelName",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."provided_model_name"',},{uiTableName: "Model ID",uiTableId: "modelId",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."model_id"',},{uiTableName: "Input Tokens",uiTableId: "inputTokens",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, usage_details)))",clickhouseTypeOverwrite: "Decimal64(3)",@@ -134,7 +134,7 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{uiTableName: "Output Tokens",uiTableId: "outputTokens",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, usage_details)))",clickhouseTypeOverwrite: "Decimal64(3)",@@ -142,7 +142,7 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{uiTableName: "Total Tokens",uiTableId: "totalTokens",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",clickhouseTypeOverwrite: "Decimal64(3)",@@ -150,7 +150,7 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{uiTableName: "Tokens",uiTableId: "tokens",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect:"if(mapExists((k, v) -> (k = 'total'), usage_details), usage_details['total'], NULL)",clickhouseTypeOverwrite: "Decimal64(3)",@@ -158,97 +158,97 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{uiTableName: "Metadata",uiTableId: "metadata",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."metadata"',},{uiTableName: "Version",uiTableId: "version",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."version"',},{uiTableName: "Prompt Name",uiTableId: "promptName",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: "e.prompt_name",},{uiTableName: "Input",uiTableId: "input",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: "e.input",},{uiTableName: "Output",uiTableId: "output",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: "e.output",},{uiTableName: "Session ID",uiTableId: "sessionId",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."session_id"',},{uiTableName: "Trace Name",uiTableId: "traceName",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."trace_name"',},{uiTableName: "User ID",uiTableId: "userId",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."user_id"',},{uiTableName: "Trace Tags",uiTableId: "traceTags",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."tags"',},{uiTableName: "Tags",uiTableId: "tags",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."tags"',},{uiTableName: "Trace Environment",uiTableId: "traceEnvironment",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."environment"',},{uiTableName: "Has Parent Observation",uiTableId: "hasParentObservation",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: "e.parent_span_id != ''",},{uiTableName: "Parent Observation ID",uiTableId: "parentObservationId",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."parent_span_id"',},{uiTableName: "Experiment Dataset ID",uiTableId: "experimentDatasetId",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."experiment_dataset_id"',},{uiTableName: "Experiment ID",uiTableId: "experimentId",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."experiment_id"',},{uiTableName: "Experiment Name",uiTableId: "experimentName",- clickhouseTableName: "events",+ clickhouseTableName: "events_proto",clickhouseSelect: 'e."experiment_name"',},];diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex 217d7c808f..4d72c762c2 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -188,11 +188,21 @@ export const createDatasetRunScore = (};export const createEvent = (- event: Partial<EventRecordInsertType>,+ event: Partial<EventRecordInsertType> & {+ metadata_values?: (string | null | undefined)[];+ },): EventRecordInsertType => {const spanId = v4();const now = Date.now() * 1000; // Convert to micro+ // Extract metadata array overrides before spreading to prevent undefined from clobbering defaults+ const {+ metadata_values: metadataValuesAlias,+ metadata_names: metadataNamesOverride,+ metadata_raw_values: metadataRawValuesOverride,+ ...eventOverrides+ } = event;+// Default metadata to populate arrays fromconst defaultMetadata: Record<string, string> = {source: "API",@@ -202,7 +212,7 @@ export const createEvent = (// Merge default metadata with any provided metadataconst finalMetadata: Record<string, string> = {...defaultMetadata,- ...event.metadata,+ ...eventOverrides.metadata,};// Extract metadata keys and values in sorted order for deterministic array population@@ -259,9 +269,11 @@ export const createEvent = (output: "Hello John",// Metadata - populate both JSON and array columns+ // metadata_values alias maps to metadata_raw_values (events table column name)metadata: finalMetadata,- metadata_names: metadataNames,- metadata_raw_values: metadataValues,+ metadata_names: metadataNamesOverride ?? metadataNames,+ metadata_raw_values:+ metadataValuesAlias ?? metadataRawValuesOverride ?? metadataValues,// Experiment propertiesexperiment_id: null,@@ -300,6 +312,6 @@ export const createEvent = (updated_at: now,event_ts: now,- ...event,+ ...eventOverrides,};};diff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/async/metrics-v2-api.servertest.tsindex 304600d6e7..e036048e8d 100644--- a/web/src/__tests__/async/metrics-v2-api.servertest.ts+++ b/web/src/__tests__/async/metrics-v2-api.servertest.ts@@ -78,7 +78,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {await waitForExpect(async () => {const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,+ query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,params: { projectId, ids: observationIds },});expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(@@ -280,7 +280,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {start_time: timeValue,total_cost: cost,metadata_names: ["test"],- metadata_raw_values: [testMetadataValue],+ metadata_values: [testMetadataValue],}),);});diff --git a/web/src/__tests__/async/observations-api-v2.servertest.ts b/web/src/__tests__/async/observations-api-v2.servertest.tsindex 2d4e9c098a..ffb71ff005 100644--- a/web/src/__tests__/async/observations-api-v2.servertest.ts+++ b/web/src/__tests__/async/observations-api-v2.servertest.ts@@ -44,7 +44,7 @@ describe("/api/public/v2/observations API Endpoint", () => {output: "The capital of France is Paris.",metadata: { source: "API" },metadata_names: ["source"],- metadata_raw_values: ["API"],+ metadata_values: ["API"],provided_model_name: "gpt-4",});@@ -281,7 +281,7 @@ describe("/api/public/v2/observations API Endpoint", () => {await waitForExpect(async () => {const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,+ query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,params: { projectId, ids: [observationId1, observationId2] },});expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(2);@@ -443,7 +443,7 @@ describe("/api/public/v2/observations API Endpoint", () => {// Nested metadata: { scope: { name: "api-server" }, region: "us-east" }metadata: { scope: { name: "api-server" }, region: "us-east" },metadata_names: ["scope.name", "region"],- metadata_raw_values: ["api-server", "us-east"],+ metadata_values: ["api-server", "us-east"],});const observation2 = createEvent({@@ -458,7 +458,7 @@ describe("/api/public/v2/observations API Endpoint", () => {// Nested metadata: { scope: { name: "ui-client" }, region: "us-west" }metadata: { scope: { name: "ui-client" }, region: "us-west" },metadata_names: ["scope.name", "region"],- metadata_raw_values: ["ui-client", "us-west"],+ metadata_values: ["ui-client", "us-west"],});await createEventsCh([observation1, observation2]);@@ -467,7 +467,7 @@ describe("/api/public/v2/observations API Endpoint", () => {await waitForExpect(async () => {const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,+ query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND span_id IN ({ids: Array(String)})`,params: { projectId, ids: [observationId1, observationId2] },});expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(2);@@ -505,10 +505,7 @@ describe("/api/public/v2/observations API Endpoint", () => {});maybe("Metadata expansion with expandMetadata parameter", () => {- // Cutoff is 200 chars - values longer than 200 chars are truncated by default- const METADATA_CUTOFF = 200;-- it("should selectively expand only specified metadata keys", async () => {+ it("should return full metadata values when expandMetadata is specified", async () => {const traceId = randomUUID();const observationId = randomUUID();const timestamp = new Date();@@ -529,11 +526,11 @@ describe("/api/public/v2/observations API Endpoint", () => {start_time: timeValue,metadata: {expandMe: longValue1,- keepTruncated: longValue2,+ otherKey: longValue2,shortKey: "shortValue",},- metadata_names: ["expandMe", "keepTruncated", "shortKey"],- metadata_raw_values: [longValue1, longValue2, "shortValue"],+ metadata_names: ["expandMe", "otherKey", "shortKey"],+ metadata_values: [longValue1, longValue2, "shortValue"],});await createEventsCh([observation]);@@ -542,7 +539,7 @@ describe("/api/public/v2/observations API Endpoint", () => {await waitForExpect(async () => {const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id = {id: String}`,+ query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND span_id = {id: String}`,params: { projectId, id: observationId },});expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);@@ -551,7 +548,7 @@ describe("/api/public/v2/observations API Endpoint", () => {10,);- // Request metadata with expansion for only 'expandMe' key+ // Request metadata with expansion - this switches to events_full tableconst response = await makeZodVerifiedAPICall(GetObservationsV2Response,"GET",@@ -562,15 +559,13 @@ describe("/api/public/v2/observations API Endpoint", () => {const obs = response.body.data.find((o: any) => o.id === observationId);expect(obs).toBeDefined();- // 'expandMe' should be full (300 chars)+ // When expandMetadata is specified, the query uses events_full table which has+ // full (non-truncated) metadata values. All metadata values are returned in full.expect(obs?.metadata?.expandMe?.length).toBe(300);expect(obs?.metadata?.expandMe).toBe(longValue1);- // 'keepTruncated' should still be truncated (200 chars)- expect(obs?.metadata?.keepTruncated?.length).toBe(METADATA_CUTOFF);- expect(obs?.metadata?.keepTruncated).toBe(- longValue2.substring(0, METADATA_CUTOFF),- );+ expect(obs?.metadata?.otherKey?.length).toBe(300);+ expect(obs?.metadata?.otherKey).toBe(longValue2);// 'shortValue' should be present as isexpect(obs?.metadata?.shortKey).toBe("shortValue");@@ -593,7 +588,7 @@ describe("/api/public/v2/observations API Endpoint", () => {start_time: timeValue,metadata: { existingKey: "value" },metadata_names: ["existingKey"],- metadata_raw_values: ["value"],+ metadata_values: ["value"],});await createEventsCh([observation]);@@ -602,7 +597,7 @@ describe("/api/public/v2/observations API Endpoint", () => {await waitForExpect(async () => {const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id = {id: String}`,+ query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND span_id = {id: String}`,params: { projectId, id: observationId },});expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);@@ -635,8 +630,10 @@ describe("/api/public/v2/observations API Endpoint", () => {const timestamp = new Date();const timeValue = timestamp.getTime() * 1000;- // Create a long metadata value (> 200 chars)+ // Create a long metadata value (> 200 chars, the MV truncation limit)const longValue = "z".repeat(300);+ // events_core MV truncates metadata values to 200 chars+ const METADATA_CUTOFF = 200;const observation = createEvent({id: observationId,@@ -649,7 +646,7 @@ describe("/api/public/v2/observations API Endpoint", () => {start_time: timeValue,metadata: { longKey: longValue },metadata_names: ["longKey"],- metadata_raw_values: [longValue],+ metadata_values: [longValue],});await createEventsCh([observation]);@@ -658,7 +655,7 @@ describe("/api/public/v2/observations API Endpoint", () => {await waitForExpect(async () => {const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND span_id = {id: String}`,+ query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND span_id = {id: String}`,params: { projectId, id: observationId },});expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(1);@@ -667,7 +664,7 @@ describe("/api/public/v2/observations API Endpoint", () => {10,);- // Request metadata with empty expandMetadata - should use truncated+ // Request metadata with empty expandMetadata - should use events_core (truncated)const response = await makeZodVerifiedAPICall(GetObservationsV2Response,"GET",@@ -678,7 +675,7 @@ describe("/api/public/v2/observations API Endpoint", () => {const obs = response.body.data.find((o: any) => o.id === observationId);expect(obs).toBeDefined();- // Metadata should still be present but truncated (empty expandMetadata means no expansion)+ // Metadata should still be present but truncated (empty expandMetadata uses events_core)expect(obs?.metadata?.longKey).toBeDefined();expect(obs?.metadata?.longKey?.length).toBe(METADATA_CUTOFF);expect(obs?.metadata?.longKey).toBe(@@ -719,7 +716,7 @@ describe("/api/public/v2/observations API Endpoint", () => {await waitForExpect(async () => {const result = await queryClickhouse<{ count: string }>({- query: `SELECT count() as count FROM events WHERE project_id = {projectId: String} AND trace_id = {traceId: String}`,+ query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND trace_id = {traceId: String}`,params: { projectId, traceId },});expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(10);diff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/async/observations-api.servertest.tsindex cca6c5d947..07cc7fa48b 100644--- a/web/src/__tests__/async/observations-api.servertest.ts+++ b/web/src/__tests__/async/observations-api.servertest.ts@@ -60,9 +60,7 @@ const createObservationData = (output: data.output !== undefined ? data.output : "Hello John",metadata: data.metadata ?? { source: "API", server: "Node" },metadata_names: data.metadata ? Object.keys(data.metadata) : undefined,- metadata_raw_values: data.metadata- ? Object.values(data.metadata)- : undefined,+ metadata_values: data.metadata ? Object.values(data.metadata) : undefined,provided_model_name: data.provided_model_name,provided_usage_details: data.provided_usage_details,provided_cost_details: data.provided_cost_details,diff --git a/web/src/__tests__/async/repositories/event-repository.servertest.ts b/web/src/__tests__/async/repositories/event-repository.servertest.tsindex a5ec8f4bcf..0bd6de19e2 100644--- a/web/src/__tests__/async/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/event-repository.servertest.ts@@ -14,6 +14,7 @@ import { prisma } from "@langfuse/shared/src/db";import { randomUUID } from "crypto";import { env } from "@/src/env.mjs";import { type FilterCondition } from "@langfuse/shared";+import waitForExpect from "wait-for-expect";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";@@ -1576,6 +1577,37 @@ describe("Clickhouse Events Repository Test", () => {expect(result).toBeDefined();expect(result?.bookmarked).toBe(false);+ async function checkTraceIdsBookmarked(+ traceId: string,+ bookmarkedExp: boolean,+ ) {+ await waitForExpect(async () => {+ // Verify events_core+ const eventTrace = await getTraceByIdFromEventsTable({+ projectId,+ traceId: traceId,+ renderingProps: {+ truncated: true,+ shouldJsonParse: false,+ },+ });+ expect(eventTrace).toBeDefined();+ expect(eventTrace?.bookmarked).toBe(bookmarkedExp);++ // Verify events_full+ const eventTraceFull = await getTraceByIdFromEventsTable({+ projectId,+ traceId: traceId,+ renderingProps: {+ truncated: false,+ shouldJsonParse: true,+ },+ });+ expect(eventTraceFull).toBeDefined();+ expect(eventTraceFull?.bookmarked).toBe(bookmarkedExp);+ });+ }+// Model setting bookmark as true on the root spanawait updateEvents(projectId,@@ -1583,9 +1615,7 @@ describe("Clickhouse Events Repository Test", () => {{ bookmarked: true },);- result = await getTraceByIdFromEventsTable({ projectId, traceId });- expect(result).toBeDefined();- expect(result?.bookmarked).toBe(true);+ await checkTraceIdsBookmarked(traceId, true);// Non-root event on bookmarkedawait createEventsCh([@@ -1609,17 +1639,10 @@ describe("Clickhouse Events Repository Test", () => {{ bookmarked: false },);- result = await getTraceByIdFromEventsTable({ projectId, traceId });- expect(result).toBeDefined();- expect(result?.bookmarked).toBe(false);+ await checkTraceIdsBookmarked(traceId, false);// Trace id 2 should remain bookmarked- result = await getTraceByIdFromEventsTable({- projectId,- traceId: traceId2,- });- expect(result).toBeDefined();- expect(result?.bookmarked).toBe(true);+ await checkTraceIdsBookmarked(traceId2, true);});it("should allow to set/unset public", async () => {@@ -1647,23 +1670,45 @@ describe("Clickhouse Events Repository Test", () => {parent_span_id: "",});+ async function checkTraceIdsPublic(traceId: string, publicExp: boolean) {+ await waitForExpect(async () => {+ // Verify events_core+ const eventTrace = await getTraceByIdFromEventsTable({+ projectId,+ traceId: traceId,+ renderingProps: {+ truncated: true,+ shouldJsonParse: false,+ },+ });+ expect(eventTrace).toBeDefined();+ expect(eventTrace?.public).toBe(publicExp);++ // Verify events_full+ const eventTraceFull = await getTraceByIdFromEventsTable({+ projectId,+ traceId: traceId,+ renderingProps: {+ truncated: false,+ shouldJsonParse: true,+ },+ });+ expect(eventTraceFull).toBeDefined();+ expect(eventTraceFull?.public).toBe(publicExp);+ });+ }+await createEventsCh([rootEvent, rootEvent2]);- var result = await getTraceByIdFromEventsTable({ projectId, traceId });- expect(result).toBeDefined();- expect(result?.public).toBe(false);+ await checkTraceIdsPublic(traceId, false);await updateEvents(projectId, { traceIds: [traceId] }, { public: true });- result = await getTraceByIdFromEventsTable({ projectId, traceId });- expect(result).toBeDefined();- expect(result?.public).toBe(true);+ await checkTraceIdsPublic(traceId, true);await updateEvents(projectId, { traceIds: [traceId] }, { public: false });- result = await getTraceByIdFromEventsTable({ projectId, traceId });- expect(result).toBeDefined();- expect(result?.public).toBe(false);+ await checkTraceIdsPublic(traceId, false);// Non-root event with publicawait createEventsCh([@@ -1678,24 +1723,16 @@ describe("Clickhouse Events Repository Test", () => {parent_span_id: rootSpanId,}),]);- result = await getTraceByIdFromEventsTable({ projectId, traceId });- expect(result).toBeDefined();- expect(result?.public).toBe(true);++ await checkTraceIdsPublic(traceId, true);// Clearing public on non-rootawait updateEvents(projectId, { traceIds: [traceId] }, { public: false });- result = await getTraceByIdFromEventsTable({ projectId, traceId });- expect(result).toBeDefined();- expect(result?.public).toBe(false);+ await checkTraceIdsPublic(traceId, false);// Trace id 2 should remain public- result = await getTraceByIdFromEventsTable({- projectId,- traceId: traceId2,- });- expect(result).toBeDefined();- expect(result?.public).toBe(true);+ await checkTraceIdsPublic(traceId2, true);});});diff --git a/web/src/__tests__/async/traces-trpc.servertest.ts b/web/src/__tests__/async/traces-trpc.servertest.tsindex c5947f3dd2..0c891c88d6 100644--- a/web/src/__tests__/async/traces-trpc.servertest.ts+++ b/web/src/__tests__/async/traces-trpc.servertest.ts@@ -16,6 +16,7 @@ import {createObservation,createObservationsCh,} from "@langfuse/shared/src/server";+import waitForExpect from "wait-for-expect";import { randomUUID } from "crypto";import { env } from "@/src/env.mjs";@@ -524,12 +525,31 @@ describe("traces trpc", () => {expect(updatedTrace?.bookmarked).toBe(true);if (useEventsTable) {- const eventTrace = await getTraceByIdFromEventsTable({- projectId,- traceId: trace.id,+ await waitForExpect(async () => {+ // Verify events_core+ const eventTrace = await getTraceByIdFromEventsTable({+ projectId,+ traceId: trace.id,+ renderingProps: {+ truncated: true,+ shouldJsonParse: false,+ },+ });+ expect(eventTrace).toBeDefined();+ expect(eventTrace?.bookmarked).toBe(true);++ // Verify events_full+ const eventTraceFull = await getTraceByIdFromEventsTable({+ projectId,+ traceId: trace.id,+ renderingProps: {+ truncated: false,+ shouldJsonParse: true,+ },+ });+ expect(eventTraceFull).toBeDefined();+ expect(eventTraceFull?.bookmarked).toBe(true);});- expect(eventTrace).toBeDefined();- expect(eventTrace?.bookmarked).toBe(true);}});@@ -586,12 +606,31 @@ describe("traces trpc", () => {expect(updatedTrace?.public).toBe(true);if (useEventsTable) {- const eventTrace = await getTraceByIdFromEventsTable({- projectId,- traceId: trace.id,+ await waitForExpect(async () => {+ // Verify events_core+ const eventTrace = await getTraceByIdFromEventsTable({+ projectId,+ traceId: trace.id,+ renderingProps: {+ truncated: true,+ shouldJsonParse: false,+ },+ });+ expect(eventTrace).toBeDefined();+ expect(eventTrace?.public).toBe(true);++ // Verify events_full+ const eventTraceFull = await getTraceByIdFromEventsTable({+ projectId,+ traceId: trace.id,+ renderingProps: {+ truncated: false,+ shouldJsonParse: true,+ },+ });+ expect(eventTraceFull).toBeDefined();+ expect(eventTraceFull?.public).toBe(true);});- expect(eventTrace).toBeDefined();- expect(eventTrace?.public).toBe(true);}});});diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.tsindex 7a84f2c120..bd7e4661da 100644--- a/web/src/features/query/dataModel.ts+++ b/web/src/features/query/dataModel.ts@@ -306,7 +306,7 @@ export const eventsTracesView: ViewDeclarationType = {segments: [],timeDimension: "start_time",timeDimensionAggregation: "min",- baseCte: `events events_traces`,+ baseCte: `events_core events_traces`,};export const observationsView: ViewDeclarationType = {@@ -841,13 +841,13 @@ const createScoreTableRelations = (} else {return {events_traces: {- name: "events",+ name: "events_core",joinConditionSql:"ON scores.trace_id = events_traces.trace_id AND scores.project_id = events_traces.project_id AND events_traces.parent_span_id = ''",timeDimension: "start_time",},events_observations: {- name: "events",+ name: "events_core",joinConditionSql:"ON scores.project_id = events_observations.project_id AND scores.trace_id = events_observations.trace_id AND scores.observation_id = events_observations.span_id",timeDimension: "start_time",@@ -1239,7 +1239,7 @@ export const eventsObservationsView: ViewDeclarationType = {},segments: [],timeDimension: "start_time",- baseCte: "events events_observations", // No FINAL modifier needed for events table+ baseCte: "events_core events_observations", // No FINAL modifier needed for events_core table};// Define versioned structure typediff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex f95e302182..a3b6849704 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -190,7 +190,7 @@ export class QueryBuilder {}private actualTableName(view: ViewDeclarationType): string {- // Extract actual table name from baseCte (handles cases like "events-observations" -> "events")+ // Extract actual table name from baseCte (e.g., "events_core events_traces" -> "events_core")return view.baseCte.split(" ")[0];}@@ -1044,7 +1044,7 @@ export class QueryBuilder {// Events table never needs FINAL modifier (already deduplicated)if (view.name === "events-observations") {- // baseCte already set to "events" in view definition (no FINAL)+ // baseCte already set to "events_core" in view definition (no FINAL)// No changes needed, just using as-is}// Skip FINAL on observations base table if OTEL projectdiff --git a/worker/src/app.ts b/worker/src/app.tsindex 2540a2f4d8..202ef8e5e4 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -569,9 +569,11 @@ export const batchProjectCleaners: BatchProjectCleaner[] = [];if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {for (const table of BATCH_DELETION_TABLES) {- // Only start the events table cleaner if the events table experiment is enabled+ // Only start the events table cleaners if the events table experiment is enabledif (- table !== "events" ||+ (table !== "events_full" &&+ table !== "events_core" &&+ table !== "events") ||env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true") {const cleaner = new BatchProjectCleaner(table);@@ -586,9 +588,11 @@ 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 cleaner if the events table experiment is enabled+ // Only start the events table cleaners if the events table experiment is enabledif (- table !== "events" ||+ (table !== "events_full" &&+ table !== "events_core" &&+ table !== "events") ||env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true") {const cleaner = new BatchDataRetentionCleaner(table);diff --git a/worker/src/features/batch-data-retention-cleaner/index.ts b/worker/src/features/batch-data-retention-cleaner/index.tsindex 4479bed91e..16d3df2727 100644--- a/worker/src/features/batch-data-retention-cleaner/index.ts+++ b/worker/src/features/batch-data-retention-cleaner/index.ts@@ -19,6 +19,8 @@ export const BATCH_DATA_RETENTION_TABLES = ["traces","observations","scores",+ "events_full",+ "events_core","events",] as const;@@ -34,6 +36,8 @@ export const TIMESTAMP_COLUMN_MAP: Record<BatchDataRetentionTable, string> = {traces: "timestamp",observations: "start_time",scores: "timestamp",+ events_full: "start_time",+ events_core: "start_time",events: "start_time",};@@ -97,7 +101,7 @@ function buildRetentionConditions(* BatchDataRetentionCleaner handles bulk deletion of ClickHouse data based on* project retention settings.*- * Each instance processes one table (traces, observations, scores, events).+ * Each instance processes one table (traces, observations, scores, events_full, events_core).* Multiple workers coordinate via Redis distributed locking to ensure only one* worker deletes from a given table at a time.*@@ -326,6 +330,8 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {HAVING count > 0`;+ const isLegacyEventsTable = this.tableName === "events";+const result = await queryClickhouse<{project_id: string;count: number;@@ -338,6 +344,7 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {table: this.tableName,operation: "count-chunk",},+ allowLegacyEventsRead: isLegacyEventsTable,});// Build maps from the resultdiff --git a/worker/src/features/batch-project-cleaner/index.ts b/worker/src/features/batch-project-cleaner/index.tsindex 0c36832b44..b9267b01d2 100644--- a/worker/src/features/batch-project-cleaner/index.ts+++ b/worker/src/features/batch-project-cleaner/index.ts@@ -11,6 +11,8 @@ export const BATCH_DELETION_TABLES = ["traces","observations","scores",+ "events_full",+ "events_core","events","dataset_run_items_rmt",] as const;@@ -30,7 +32,7 @@ interface ProjectCount {/*** BatchProjectCleaner handles bulk deletion of ClickHouse data for soft-deleted projects.*- * Each instance processes one table (traces, observations, scores, events).+ * Each instance processes one table (traces, observations, scores, events_full, events_core).* Multiple workers coordinate via Redis distributed locking to ensure only one* worker deletes from a given table at a time.*@@ -225,6 +227,7 @@ export class BatchProjectCleaner extends PeriodicExclusiveRunner {table: this.tableName,operation: "count",},+ allowLegacyEventsRead: this.tableName === "events",});const counts = new Map<string, number>();diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex 4b5d368d68..2152a7ba7b 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -130,7 +130,7 @@ export const getEventsStream = async (props: {const eventsQuery = new EventsQueryBuilder({ projectId }).selectFieldSet("export").selectIO(false) // Full I/O, no truncation- .selectMetadataDirect() // Use direct JSON metadata column+ .selectMetadataExpanded() // Full metadata values from events_full.selectRaw("s.scores_avg as scores_avg","s.score_categories as score_categories",diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.tsindex b0974276ee..4ed7477e9f 100644--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts@@ -159,6 +159,7 @@ export async function getDatasetRunItemsSinceLastRun(feature: "experiment-backfill",operation_name: "getDatasetRunItemsSinceLastRun",},+ allowLegacyEventsRead: true,});logger.info(