Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: insert directly into events_full table (#12081)

Steffen Schmitz1c8331ffc01f
diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.sh
index c57175ce4b..a6f3c2468c 100644
--- a/packages/shared/clickhouse/scripts/dev-tables.sh
+++ b/packages/shared/clickhouse/scripts/dev-tables.sh
@@ -129,173 +129,6 @@ ORDER BY (
TTL s3_first_seen_timestamp + INTERVAL 12 HOUR
SETTINGS ttl_only_drop_parts = 1;
--- Create original events table for development setups.
-CREATE TABLE IF NOT EXISTS events
- (
- 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),
- bookmarked Bool DEFAULT false,
- public Bool DEFAULT false,
-
- level LowCardinality(String),
- status_message String, -- Threat '' and null the same for search
- completion_start_time Nullable(DateTime64(6)),
-
- -- Prompt
- prompt_id String,
- prompt_name String,
- prompt_version Nullable(UInt16),
-
- -- Model
- model_id String,
- provided_model_name String,
- model_parameters String,
- model_parameters_json JSON MATERIALIZED model_parameters::JSON,
-
- -- Usage
- provided_usage_details Map(LowCardinality(String), UInt64),
- provided_usage_details_json JSON(max_dynamic_paths=64, max_dynamic_types=8) MATERIALIZED provided_usage_details::JSON,
- usage_details Map(LowCardinality(String), UInt64),
- usage_details_json JSON(
- max_dynamic_paths=64,
- max_dynamic_types=8,
- input UInt64,
- output UInt64,
- total UInt64,
- ) MATERIALIZED usage_details::JSON,
- provided_cost_details Map(LowCardinality(String), Decimal(18,12)),
- provided_cost_details_json JSON(max_dynamic_paths=64, max_dynamic_types=8) MATERIALIZED provided_cost_details::JSON,
- cost_details Map(LowCardinality(String), Decimal(18,12)),
- cost_details_json JSON(
- max_dynamic_paths=64,
- max_dynamic_types=8,
- input Decimal(18,12),
- output Decimal(18,12),
- total Decimal(18,12),
- ) MATERIALIZED cost_details::JSON,
-
- 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_json.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_truncated String MATERIALIZED leftUTF8(input, 1024),
- input_length UInt64 MATERIALIZED lengthUTF8(input),
- output String CODEC(ZSTD(3)),
- output_truncated String MATERIALIZED leftUTF8(output, 1024),
- output_length UInt64 MATERIALIZED lengthUTF8(output),
-
- -- Metadata
- -- Keep raw JSON to benefit from future ClickHouse improvements.
- -- For now, store things as "German Strings" with fast prefix matches based on https://www.uber.com/en-DE/blog/logging/.
- metadata JSON(max_dynamic_paths=0),
- metadata_names Array(String),
- metadata_raw_values Array(String), -- should not be used on retrieval, only for materializing other columns
- metadata_prefixes Array(String) MATERIALIZED arrayMap(v -> leftUTF8(CAST(v, 'String'), 200), metadata_raw_values),
- metadata_hashes Array(Nullable(UInt32)) MATERIALIZED arrayMap(v -> if(lengthUTF8(CAST(v, 'String')) > 200, xxHash32(CAST(v, 'String')), NULL), metadata_raw_values),
- metadata_long_values Map(UInt32, String) MATERIALIZED mapFromArrays(
- arrayMap(v -> xxHash32(CAST(v, 'String')), arrayFilter(v -> lengthUTF8(CAST(v, 'String')) > 200, metadata_raw_values)),
- arrayMap(v -> CAST(v, 'String'), arrayFilter(v -> lengthUTF8(CAST(v, 'String')) > 200, metadata_raw_values))
- ),
-
- -- Experiment properties
- experiment_id String,
- experiment_name String,
- experiment_metadata_names Array(String),
- experiment_metadata_values Array(String), -- We will restrict this to 200 characters on the client.
- experiment_description String,
- experiment_dataset_id String,
- experiment_item_id String,
- experiment_item_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, start_time, xxHash32(trace_id))
- ORDER BY (project_id, start_time, xxHash32(trace_id), span_id)
- SAMPLE BY xxHash32(trace_id)
- SETTINGS
- index_granularity = 8192,
- index_granularity_bytes = '64Mi', -- Default 10MiB. Avoid small granules due to large rows.
- enable_block_number_column = 1,
- enable_block_offset_column = 1,
- dynamic_serialization_version='v3',
- object_serialization_version='v3',
- object_shared_data_serialization_version='advanced',
- object_shared_data_serialization_version_for_zero_level_parts='map_with_buckets'
- -- Try without, but re-enable if recent row performance is bad
- -- min_rows_for_wide_part = 0,
- -- 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.
@@ -623,75 +456,6 @@ SELECT
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;
-
CREATE VIEW analytics_events_core AS
SELECT
project_id,
@@ -741,7 +505,6 @@ clickhouse client \
--database="${CLICKHOUSE_DB}" \
--multiquery <<EOF
SET type_json_skip_duplicated_paths = 1;
- TRUNCATE events;
TRUNCATE events_core;
TRUNCATE events_full;
@@ -749,13 +512,13 @@ clickhouse client \
-- and re-inserts them with experiment metadata via handleExperimentBackfill.
-- For dev seeding, we include all traces directly to ensure events_core and
-- traces/observations tables have matching row counts for dashboard testing.
- INSERT INTO events (project_id, trace_id, span_id, parent_span_id, start_time, end_time, name, type,
+ INSERT INTO events_full (project_id, trace_id, span_id, parent_span_id, start_time, end_time, name, type,
environment, version, release, tags, trace_name, user_id, session_id, public, bookmarked, level, status_message, completion_start_time, prompt_id,
prompt_name, prompt_version, model_id, provided_model_name, model_parameters,
provided_usage_details, usage_details, provided_cost_details, cost_details,
usage_pricing_tier_id, usage_pricing_tier_name,
tool_definitions, tool_calls, tool_call_names, input,
- output, metadata, metadata_names, metadata_raw_values,
+ output, metadata_names, metadata_values,
source, blob_storage_file_path, event_bytes,
created_at, updated_at, event_ts, is_deleted)
SELECT o.project_id,
@@ -798,9 +561,8 @@ clickhouse client \
o.tool_call_names,
coalesce(o.input, '') AS input,
coalesce(o.output, '') AS output,
- CAST(mapConcat(o.metadata, coalesce(t.metadata, map())), 'JSON(max_dynamic_paths=0)') AS metadata,
mapKeys(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_names,
- mapValues(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_raw_values,
+ mapValues(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_values,
multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-dual-write', 'ingestion-api-dual-write') AS source,
'' AS blob_storage_file_path,
byteSize(*) AS event_bytes,
@@ -811,16 +573,17 @@ clickhouse client \
FROM observations o FINAL
LEFT JOIN traces t ON o.project_id = t.project_id AND o.trace_id = t.id
WHERE (o.is_deleted = 0);
+
-- Backfill events from traces table as well
-- Traces are converted to synthetic observations with id = 't-' + trace_id
-- (matching convertTraceToStagingObservation in the ingestion pipeline)
- INSERT INTO events (project_id, trace_id, span_id, parent_span_id, start_time, name, type,
+ INSERT INTO events_full (project_id, trace_id, span_id, parent_span_id, start_time, name, type,
environment, version, release, tags, trace_name, user_id, session_id, public, bookmarked, level,
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, metadata_names, metadata_raw_values,
+ metadata_names, metadata_values,
source, blob_storage_file_path, event_bytes,
created_at, updated_at, event_ts, is_deleted)
SELECT t.project_id,
@@ -852,9 +615,8 @@ clickhouse client \
[],
coalesce(t.input, '') AS input,
coalesce(t.output, '') AS output,
- CAST(t.metadata, 'JSON(max_dynamic_paths=0)'),
mapKeys(t.metadata) AS metadata_names,
- mapValues(t.metadata) AS metadata_raw_values,
+ mapValues(t.metadata) AS metadata_values,
multiIf(mapContains(t.metadata, 'resourceAttributes'), 'otel-dual-write', 'ingestion-api-dual-write') AS source,
'' AS blob_storage_file_path,
byteSize(*) AS event_bytes,
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 9ab8de6437..39532a249a 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -324,11 +324,6 @@ 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 License
LANGFUSE_EE_LICENSE_KEY: z.string().optional(),
diff --git a/packages/shared/src/features/evals/observationForEval.ts b/packages/shared/src/features/evals/observationForEval.ts
index bb71ad2919..971b052afe 100644
--- a/packages/shared/src/features/evals/observationForEval.ts
+++ b/packages/shared/src/features/evals/observationForEval.ts
@@ -2,6 +2,7 @@ import { z } from "zod/v4";
import { DEFAULT_TRACE_ENVIRONMENT } from "../../server/ingestion/types";
import { type EventRecordBaseType } from "../../server/repositories/definitions";
import { ObservationLevel, ObservationType } from "../../domain";
+import { metadataArraysToRecord } from "../../server/utils/metadata_conversion";
import { SingleValueOption } from "../../tableDefinitions";
import { ColumnDefinition } from "../../tableDefinitions";
import { formatColumnOptions } from "../../tableDefinitions/typeHelpers";
@@ -74,7 +75,15 @@ export type ObservationForEval = z.infer<typeof observationForEvalSchema>;
export function convertEventRecordToObservationForEval(
record: EventRecordBaseType,
): ObservationForEval {
- return observationForEvalSchema.parse(record);
+ const metadata = metadataArraysToRecord(
+ record.metadata_names,
+ record.metadata_values,
+ );
+
+ return observationForEvalSchema.parse({
+ ...record,
+ metadata,
+ });
}
export type ObservationEvalFilterColumnInternal =
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 108e6ba2dc..468356423a 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -99,6 +99,7 @@ export * from "./queries/clickhouse-sql/query-options";
export * from "./repositories";
export * from "./repositories/traces";
export * from "./repositories/dataset-items";
+export * from "./utils/metadata_conversion";
export * from "./utils/rendering";
export * from "./utils/sqlLike";
export * from "./redis/evalExecutionQueue";
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index f56f00bff1..d680aecfa6 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -96,22 +96,6 @@ 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: {
@@ -225,10 +209,7 @@ 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,
@@ -366,10 +347,7 @@ 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.ts
index e0e86d8aea..64f91ff3cd 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -687,8 +687,8 @@ export const eventRecordBaseSchema = z.object({
output: z.string().nullish(),
// Metadata
- metadata: z.record(z.string(), z.string()),
metadata_names: z.array(z.string()).default([]),
+ metadata_values: z.array(z.string()).default([]),
// Experiment properties
experiment_id: z.string().nullish(),
@@ -724,9 +724,6 @@ export const eventRecordBaseSchema = z.object({
export type EventRecordBaseType = z.infer<typeof eventRecordBaseSchema>;
export const eventRecordReadSchema = eventRecordBaseSchema.extend({
- 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(),
start_time: clickhouseStringDateSchema,
@@ -739,7 +736,6 @@ export const eventRecordReadSchema = eventRecordBaseSchema.extend({
export type EventRecordReadType = z.infer<typeof eventRecordReadSchema>;
export const eventRecordInsertSchema = eventRecordBaseSchema.extend({
- metadata_raw_values: z.array(z.string().nullish()).default([]),
start_time: z.number(),
end_time: z.number().nullish(),
completion_start_time: z.number().nullish(),
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 3a00f7704b..f2a3cfff2f 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -76,21 +76,6 @@ import { eventsTableCols } from "../../eventsTable";
import { tracesTableCols } from "../../tableDefinitions/tracesTable";
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"
@@ -1505,7 +1490,6 @@ export const updateEvents = async (
await Promise.all([
commandClickhouse(updateOpts("events_full")),
commandClickhouse(updateOpts("events_core")),
- commandLegacyEventsTable(updateOpts("events")),
]);
};
@@ -2412,7 +2396,6 @@ export const deleteEventsByTraceIds = async (
await Promise.all([
commandClickhouse(deleteOpts("events_full")),
commandClickhouse(deleteOpts("events_core")),
- commandLegacyEventsTable(deleteOpts("events")),
]);
};
@@ -2464,7 +2447,6 @@ export const deleteEventsByProjectId = async (
await Promise.all([
commandClickhouse(deleteOpts("events_full")),
commandClickhouse(deleteOpts("events_core")),
- commandLegacyEventsTable(deleteOpts("events")),
]);
return true;
@@ -2579,7 +2561,6 @@ export const deleteEventsOlderThanDays = async (
await Promise.all([
commandClickhouse(deleteOpts("events_full")),
commandClickhouse(deleteOpts("events_core")),
- commandLegacyEventsTable(deleteOpts("events")),
]);
return true;
diff --git a/packages/shared/src/server/test-utils/clickhouse-helpers.ts b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
index 0192dbd4ff..900c496009 100644
--- a/packages/shared/src/server/test-utils/clickhouse-helpers.ts
+++ b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
@@ -27,7 +27,7 @@ export const createObservationsCh = async (
export const createEventsCh = async (events: EventRecordInsertType[]) => {
return await clickhouseClient().insert({
- table: "events",
+ table: "events_full",
format: "JSONEachRow",
values: events,
});
diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.ts
index 4d72c762c2..4d4ed1f99f 100644
--- a/packages/shared/src/server/test-utils/tracing-factory.ts
+++ b/packages/shared/src/server/test-utils/tracing-factory.ts
@@ -199,7 +199,6 @@ export const createEvent = (
const {
metadata_values: metadataValuesAlias,
metadata_names: metadataNamesOverride,
- metadata_raw_values: metadataRawValuesOverride,
...eventOverrides
} = event;
@@ -209,16 +208,10 @@ export const createEvent = (
server: "Node",
};
- // Merge default metadata with any provided metadata
- const finalMetadata: Record<string, string> = {
- ...defaultMetadata,
- ...eventOverrides.metadata,
- };
-
// Extract metadata keys and values in sorted order for deterministic array population
- const sortedKeys = Object.keys(finalMetadata).sort();
+ const sortedKeys = Object.keys(defaultMetadata).sort();
const metadataNames = sortedKeys;
- const metadataValues = sortedKeys.map((key) => finalMetadata[key]);
+ const metadataValues = sortedKeys.map((key) => defaultMetadata[key]);
return {
// Identifiers
@@ -268,12 +261,9 @@ export const createEvent = (
input: "Hello World",
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
metadata_names: metadataNamesOverride ?? metadataNames,
- metadata_raw_values:
- metadataValuesAlias ?? metadataRawValuesOverride ?? metadataValues,
+ metadata_values: metadataValuesAlias ?? metadataValues,
// Experiment properties
experiment_id: null,
diff --git a/packages/shared/src/server/utils/metadata_conversion.ts b/packages/shared/src/server/utils/metadata_conversion.ts
index cd76910097..af9df1a0ad 100644
--- a/packages/shared/src/server/utils/metadata_conversion.ts
+++ b/packages/shared/src/server/utils/metadata_conversion.ts
@@ -1,6 +1,28 @@
import { parseJsonPrioritised } from "../../utils/json";
import { MetadataDomain } from "../../domain";
+/**
+ * Zips parallel ClickHouse array columns (`metadata_names`, `metadata_values`)
+ * into a plain object. If a key appears more than once the **first** occurrence
+ * wins, matching the ClickHouse `mapFromArrays(arrayReverse(...))` convention.
+ *
+ * Returns `undefined` when the names array is empty so callers can distinguish
+ * "no metadata" from "empty metadata object".
+ */
+export function metadataArraysToRecord(
+ names: string[],
+ values: string[],
+): Record<string, string> | undefined {
+ if (names.length === 0) return undefined;
+
+ return names.reduce<Record<string, string>>((acc, name, i) => {
+ if (!(name in acc)) {
+ acc[name] = values[i];
+ }
+ return acc;
+ }, {});
+}
+
export function parseMetadataCHRecordToDomain(
metadata: Record<string, string>,
): MetadataDomain {
diff --git a/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts
index fe0a33adac..8826788232 100644
--- a/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts
+++ b/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts
@@ -186,7 +186,7 @@ const SEED_PROJECT_ID = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
async function seedFromSeeder(targetProjectId: string) {
const client = clickhouseClient();
- for (const table of ["traces", "observations", "events", "scores"]) {
+ for (const table of ["traces", "observations", "events_full", "scores"]) {
try {
await client.command({
query: `INSERT INTO ${table} SELECT * REPLACE({newProjectId: String} AS project_id) FROM ${table} FINAL WHERE project_id = {seedProjectId: String}`,
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index bc8bdcf4d2..2e1eb06810 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -973,7 +973,8 @@ describe("Clickhouse Events Repository Test", () => {
trace_id: traceId,
type: "SPAN",
name: "md1",
- metadata: { source: "api-server", region: "us-east" },
+ metadata_names: ["source", "region"],
+ metadata_values: ["api-server", "us-east"],
start_time: now * 1000,
}),
createEvent({
@@ -983,7 +984,8 @@ describe("Clickhouse Events Repository Test", () => {
trace_id: traceId,
type: "SPAN",
name: "md2",
- metadata: { source: "UI", region: "us-east" },
+ metadata_names: ["source", "region"],
+ metadata_values: ["UI", "us-east"],
start_time: now * 1000,
}),
createEvent({
@@ -993,7 +995,8 @@ describe("Clickhouse Events Repository Test", () => {
trace_id: traceId,
type: "SPAN",
name: "md3",
- metadata: { source: "UI", region: "us-west" },
+ metadata_names: ["source", "region"],
+ metadata_values: ["UI", "us-west"],
start_time: now * 1000,
}),
];
@@ -1953,7 +1956,8 @@ describe("Clickhouse Events Repository Test", () => {
name: "test-observation-1",
input: "This is input for observation 1",
output: "This is output for observation 1",
- metadata: { key1: "value1", source: "test" },
+ metadata_names: ["key1", "source"],
+ metadata_values: ["value1", "test"],
start_time: nowMicro,
}),
createEvent({
@@ -1965,7 +1969,8 @@ describe("Clickhouse Events Repository Test", () => {
name: "test-observation-2",
input: "This is input for observation 2",
output: "This is output for observation 2",
- metadata: { key2: "value2", environment: "production" },
+ metadata_names: ["key2", "environment"],
+ metadata_values: ["value2", "production"],
start_time: nowMicro + 1000,
}),
createEvent({
@@ -1977,7 +1982,8 @@ describe("Clickhouse Events Repository Test", () => {
name: "test-observation-3",
input: "This is input for observation 3",
output: "This is output for observation 3",
- metadata: { key3: "value3" },
+ metadata_names: ["key3"],
+ metadata_values: ["value3"],
start_time: nowMicro + 2000,
}),
];
diff --git a/web/src/__tests__/server/traces-api.servertest.ts b/web/src/__tests__/server/traces-api.servertest.ts
index edd5f50528..b366152e3a 100644
--- a/web/src/__tests__/server/traces-api.servertest.ts
+++ b/web/src/__tests__/server/traces-api.servertest.ts
@@ -128,7 +128,8 @@ const createTraceWithObservations = async (
user_id: trace.user_id ?? null,
input: trace.input ?? null,
output: trace.output ?? null,
- metadata: trace.metadata ?? {},
+ metadata_names: Object.keys(trace.metadata ?? {}) ?? [],
+ metadata_values: Object.values(trace.metadata ?? {}) ?? [],
cost_details: {
total: 0, // Root trace event has no cost
},
diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.ts
index 5db3e6b7ee..bed1e7029b 100644
--- a/worker/src/__tests__/batchAction.test.ts
+++ b/worker/src/__tests__/batchAction.test.ts
@@ -611,14 +611,16 @@ maybeDescribe("events table batch actions", () => {
trace_id: traceId,
input: eventInput1,
output: eventOutput1,
- metadata: { source: "test" },
+ metadata_names: ["source"],
+ metadata_values: ["test"],
});
const event2 = createEvent({
project_id: projectId,
trace_id: traceId,
input: eventInput2,
output: eventOutput2,
- metadata: { source: "test" },
+ metadata_names: ["source"],
+ metadata_values: ["test"],
});
await createEventsCh([event1, event2]);
@@ -728,7 +730,8 @@ maybeDescribe("events table batch actions", () => {
trace_id: traceId,
input: eventInput,
output: eventOutput,
- metadata: eventMetadata,
+ metadata_names: Object.keys(eventMetadata),
+ metadata_values: Object.values(eventMetadata),
});
await createEventsCh([event]);
diff --git a/worker/src/app.ts b/worker/src/app.ts
index af8a187a4f..b97a86ca48 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -603,9 +603,7 @@ if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {
for (const table of BATCH_DELETION_TABLES) {
// Only start the events table cleaners if the events table experiment is enabled
if (
- (table !== "events_full" &&
- table !== "events_core" &&
- table !== "events") ||
+ (table !== "events_full" && table !== "events_core") ||
env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"
) {
const cleaner = new BatchProjectCleaner(table);
@@ -622,9 +620,7 @@ if (env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_ENABLED === "true") {
for (const table of BATCH_DATA_RETENTION_TABLES) {
// Only start the events table cleaners if the events table experiment is enabled
if (
- (table !== "events_full" &&
- table !== "events_core" &&
- table !== "events") ||
+ (table !== "events_full" && table !== "events_core") ||
env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"
) {
const cleaner = new BatchDataRetentionCleaner(table);
diff --git a/worker/src/backgroundMigrations/backfillEventsHistoric.ts b/worker/src/backgroundMigrations/backfillEventsHistoric.ts
index 64a0eb22cb..f5c240193b 100644
--- a/worker/src/backgroundMigrations/backfillEventsHistoric.ts
+++ b/worker/src/backgroundMigrations/backfillEventsHistoric.ts
@@ -229,7 +229,7 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {
const requiredTables = [
"observations_pid_tid_sorting",
"traces_pid_tid_sorting",
- "events",
+ "events_full",
"backfill_chunks",
];
@@ -432,16 +432,15 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {
: `o.metadata`;
return `
- INSERT INTO events (
+ INSERT INTO events_full (
project_id, trace_id, span_id, parent_span_id, start_time, end_time,
name, type, environment, version, release, tags, public, bookmarked,
trace_name, user_id, session_id, level, status_message, completion_start_time,
prompt_id, prompt_name, prompt_version, model_id, provided_model_name,
model_parameters, provided_usage_details, usage_details,
provided_cost_details, cost_details, tool_definitions, tool_calls, tool_call_names,
- input, output, metadata,
-
- metadata_names, metadata_raw_values, source,
+ input, output,
+ metadata_names, metadata_values, source,
blob_storage_file_path, event_bytes, created_at, updated_at, event_ts, is_deleted
)
SELECT
@@ -481,9 +480,8 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {
coalesce(o.input, '') AS input,
coalesce(o.output, '') AS output,
- CAST(${metadataExpr}, 'JSON(max_dynamic_paths=0)') AS metadata,
mapKeys(${metadataExpr}) AS metadata_names,
- mapValues(${metadataExpr}) AS metadata_raw_values,
+ mapValues(${metadataExpr}) AS metadata_values,
multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,
'' AS blob_storage_file_path,
0 AS event_bytes,
@@ -642,17 +640,17 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {
};
}
- // Check if ClickHouse events table exists
+ // Check if ClickHouse events_full table exists
const tables = await clickhouseClient().query({
query: "SHOW TABLES",
});
const tableNames = (await tables.json()).data as { name: string }[];
- if (!tableNames.some((r) => r.name === "events")) {
+ if (!tableNames.some((r) => r.name === "events_full")) {
// Retry if the table does not exist as this may mean migrations are still pending
if (attempts > 0) {
logger.info(
- `ClickHouse events table does not exist. Retrying in 10s...`,
+ `ClickHouse events_full table does not exist. Retrying in 10s...`,
);
return new Promise((resolve) => {
setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);
@@ -661,7 +659,7 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {
return {
valid: false,
- invalidReason: "ClickHouse events table does not exist",
+ invalidReason: "ClickHouse events_full table does not exist",
};
}
diff --git a/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts b/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts
index a1fd75c5f7..208f84a39e 100644
--- a/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts
+++ b/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts
@@ -116,7 +116,8 @@ export default class BackfillEventsHistoricFromParts
const requiredTables = [
"observations_pid_tid_sorting",
"traces_pid_tid_sorting",
- "events",
+ "events_full",
+ "events_core",
];
for (const table of requiredTables) {
@@ -159,7 +160,8 @@ export default class BackfillEventsHistoricFromParts
FROM system.parts
WHERE database = 'default'
AND table = 'observations_pid_tid_sorting'
- and active = 1
+ AND active = 1
+ AND partition_id IN ('202602', '202601')
ORDER BY partition_id DESC
`,
tags: {
@@ -286,15 +288,15 @@ export default class BackfillEventsHistoricFromParts
private buildQuery(todo: ChunkTodo): string {
return `
- INSERT INTO events (
+ INSERT INTO events_full (
project_id, trace_id, span_id, parent_span_id, start_time, end_time,
name, type, environment, version, release, tags, public, bookmarked,
trace_name, user_id, session_id, level, status_message, completion_start_time,
prompt_id, prompt_name, prompt_version, model_id, provided_model_name,
model_parameters, provided_usage_details, usage_details,
- provided_cost_details, cost_details, tool_definitions, tool_calls, tool_call_names,
- input, output, metadata,
- metadata_names, metadata_raw_values, source,
+ provided_cost_details, cost_details, usage_pricing_tier_id, usage_pricing_tier_name,
+ tool_definitions, tool_calls, tool_call_names,
+ input, output, metadata_names, metadata_values, source,
blob_storage_file_path, event_bytes, created_at, updated_at, event_ts, is_deleted
)
SELECT
@@ -328,14 +330,15 @@ export default class BackfillEventsHistoricFromParts
o.usage_details,
o.provided_cost_details,
o.cost_details,
+ o.usage_pricing_tier_id,
+ o.usage_pricing_tier_name,
o.tool_definitions,
o.tool_calls,
o.tool_call_names,
coalesce(o.input, '') AS input,
coalesce(o.output, '') AS output,
- CAST(mapApply((k, v) -> (k, if(isValidUTF8(v), v, toValidUTF8(v))), o.metadata), 'JSON(max_dynamic_paths=0)') AS metadata,
mapKeys(o.metadata) AS metadata_names,
- mapValues(o.metadata) AS metadata_raw_values,
+ mapValues(o.metadata) AS metadata_values,
multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,
'' AS blob_storage_file_path,
0 AS event_bytes,
@@ -348,6 +351,8 @@ export default class BackfillEventsHistoricFromParts
ON o.project_id = t.project_id AND o.trace_id = t.id
WHERE o._partition_id = '${todo.partition}'
AND o._part = '${todo.partId}'
+ AND o.start_time >= toDateTime64('2026-01-20 00:00:00', 3)
+ AND o.start_time < toDateTime64('2026-02-22 00:00:00', 3)
SETTINGS
join_algorithm = 'full_sorting_merge',
type_json_skip_duplicated_paths = 1
@@ -387,8 +392,10 @@ export default class BackfillEventsHistoricFromParts
}
: retryCount === 0
? {
- min_insert_block_size_rows: "10485450",
- min_insert_block_size_bytes: "4Gi",
+ min_insert_block_size_rows: "5485450",
+ min_insert_block_size_bytes: "2Gi",
+ max_threads: 32,
+ max_block_size: "8192",
}
: {};
@@ -493,17 +500,17 @@ export default class BackfillEventsHistoricFromParts
};
}
- // Check if ClickHouse events table exists
+ // Check if ClickHouse events_full table exists
const tables = await clickhouseClient().query({
query: "SHOW TABLES",
});
const tableNames = (await tables.json()).data as { name: string }[];
- if (!tableNames.some((r) => r.name === "events")) {
+ if (!tableNames.some((r) => r.name === "events_full")) {
// Retry if the table does not exist as this may mean migrations are still pending
if (attempts > 0) {
logger.info(
- `ClickHouse events table does not exist. Retrying in 10s...`,
+ `ClickHouse events_full table does not exist. Retrying in 10s...`,
);
return new Promise((resolve) => {
setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);
@@ -512,7 +519,7 @@ export default class BackfillEventsHistoricFromParts
return {
valid: false,
- invalidReason: "ClickHouse events table does not exist",
+ invalidReason: "ClickHouse events_full table does not exist",
};
}
diff --git a/worker/src/backgroundMigrations/backfillExperimentsHistoric.ts b/worker/src/backgroundMigrations/backfillExperimentsHistoric.ts
index 76af41be50..1f69db3022 100644
--- a/worker/src/backgroundMigrations/backfillExperimentsHistoric.ts
+++ b/worker/src/backgroundMigrations/backfillExperimentsHistoric.ts
@@ -367,7 +367,7 @@ export default class BackfillExperimentsHistoric
const tables = await clickhouseClient().query({ query: "SHOW TABLES" });
const tableNames = (await tables.json()).data as { name: string }[];
- const requiredTables = ["events", "dataset_run_items_rmt"];
+ const requiredTables = ["events_full", "dataset_run_items_rmt"];
for (const tableName of requiredTables) {
if (!tableNames.some((r) => r.name === tableName)) {
@@ -518,11 +518,11 @@ export default class BackfillExperimentsHistoric
);
}
- // Write enriched spans to events table
+ // Write enriched spans to events_full table
if (allEnrichedSpans.length > 0) {
await writeEnrichedSpans(allEnrichedSpans);
logger.info(
- `[Backfill Experiments] Wrote ${allEnrichedSpans.length} enriched spans to events table`,
+ `[Backfill Experiments] Wrote ${allEnrichedSpans.length} enriched spans to events_full table`,
);
}
diff --git a/worker/src/features/batch-data-retention-cleaner/index.ts b/worker/src/features/batch-data-retention-cleaner/index.ts
index 16d3df2727..bd9b341b38 100644
--- a/worker/src/features/batch-data-retention-cleaner/index.ts
+++ b/worker/src/features/batch-data-retention-cleaner/index.ts
@@ -21,7 +21,6 @@ export const BATCH_DATA_RETENTION_TABLES = [
"scores",
"events_full",
"events_core",
- "events",
] as const;
export type BatchDataRetentionTable =
@@ -38,7 +37,6 @@ export const TIMESTAMP_COLUMN_MAP: Record<BatchDataRetentionTable, string> = {
scores: "timestamp",
events_full: "start_time",
events_core: "start_time",
- events: "start_time",
};
interface ProjectWorkload {
@@ -330,8 +328,6 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
HAVING count > 0
`;
- const isLegacyEventsTable = this.tableName === "events";
-
const result = await queryClickhouse<{
project_id: string;
count: number;
@@ -344,7 +340,6 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
table: this.tableName,
operation: "count-chunk",
},
- allowLegacyEventsRead: isLegacyEventsTable,
});
// Build maps from the result
diff --git a/worker/src/features/batch-project-cleaner/index.ts b/worker/src/features/batch-project-cleaner/index.ts
index ecf266322b..266fe550f6 100644
--- a/worker/src/features/batch-project-cleaner/index.ts
+++ b/worker/src/features/batch-project-cleaner/index.ts
@@ -13,7 +13,6 @@ export const BATCH_DELETION_TABLES = [
"scores",
"events_full",
"events_core",
- "events",
"dataset_run_items_rmt",
] as const;
import { env } from "../../env";
@@ -219,7 +218,6 @@ 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/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.ts
index 37e44e2a1b..93a04ecedf 100644
--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts
+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts
@@ -175,7 +175,7 @@ export const handleEventPropagationJob = async (
limit 1 by t.project_id, t.id
)
- INSERT INTO events (
+ INSERT INTO events_full (
project_id,
trace_id,
span_id,
@@ -214,9 +214,8 @@ export const handleEventPropagationJob = async (
input,
output,
- metadata,
metadata_names,
- metadata_raw_values,
+ metadata_values,
source,
blob_storage_file_path,
event_bytes,
@@ -271,9 +270,8 @@ export const handleEventPropagationJob = async (
coalesce(obs.input, '') AS input,
coalesce(obs.output, '') AS output,
-- Merge trace and observation metadata, with observation taking precedence (first map wins)
- CAST(mapConcat(obs.metadata, coalesce(t.metadata, map())), 'JSON(max_dynamic_paths=0)') AS metadata,
mapKeys(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_names,
- mapValues(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_raw_values,
+ mapValues(mapConcat(obs.metadata, coalesce(t.metadata, map()))) AS metadata_values,
multiIf(mapContains(obs.metadata, 'resourceAttributes'), 'otel-dual-write', 'ingestion-api-dual-write') AS source,
'' AS blob_storage_file_path,
byteSize(*) AS event_bytes,
diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
index 4ed7477e9f..b890b91b07 100644
--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts
+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
@@ -115,7 +115,7 @@ export async function getDatasetRunItemsSinceLastRun(
const query = `
WITH prefiltered_events as (
select distinct project_id, trace_id
- from events
+ from events_core
where start_time > {lastRun: DateTime64(3)} - interval 1 day
and project_id in (
select distinct project_id
@@ -159,7 +159,6 @@ export async function getDatasetRunItemsSinceLastRun(
feature: "experiment-backfill",
operation_name: "getDatasetRunItemsSinceLastRun",
},
- allowLegacyEventsRead: true,
});
logger.info(
@@ -476,7 +475,7 @@ export function enrichSpansWithExperiment(
}
/**
- * Write enriched spans to the events table using IngestionService.writeEventRecord().
+ * Write enriched spans to the events_full table using IngestionService.writeEventRecord().
* Converts EnrichedSpan to EventInput format.
*/
export async function writeEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {
@@ -583,7 +582,7 @@ export async function writeEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {
}
logger.info(
- `[EXPERIMENT BACKFILL] Wrote ${spans.length} enriched spans to events table via IngestionService`,
+ `[EXPERIMENT BACKFILL] Wrote ${spans.length} enriched spans to events_full table via IngestionService`,
);
}
@@ -882,7 +881,7 @@ async function processExperimentBackfill(
}
}
- // Write enriched spans to events table
+ // Write enriched spans to events_full table
if (allEnrichedSpans.length > 0) {
await writeEnrichedSpans(allEnrichedSpans);
}
diff --git a/worker/src/queues/__tests__/metadata_conversion.test.ts b/worker/src/queues/__tests__/metadata_conversion.test.ts
new file mode 100644
index 0000000000..4d5556f676
--- /dev/null
+++ b/worker/src/queues/__tests__/metadata_conversion.test.ts
@@ -0,0 +1,26 @@
+import { describe, it, expect } from "vitest";
+import { metadataArraysToRecord } from "@langfuse/shared/src/server";
+
+describe("metadataArraysToRecord", () => {
+ it("should return undefined for empty arrays", () => {
+ expect(metadataArraysToRecord([], [])).toBeUndefined();
+ });
+
+ it("should zip names and values into a record", () => {
+ const result = metadataArraysToRecord(["env", "version"], ["prod", "1.0"]);
+ expect(result).toEqual({ env: "prod", version: "1.0" });
+ });
+
+ it("should keep the first occurrence when keys are duplicated", () => {
+ const result = metadataArraysToRecord(
+ ["env", "env", "env"],
+ ["first", "second", "third"],
+ );
+ expect(result).toEqual({ env: "first" });
+ });
+
+ it("should handle a single entry", () => {
+ const result = metadataArraysToRecord(["key"], ["value"]);
+ expect(result).toEqual({ key: "value" });
+ });
+});
diff --git a/worker/src/queues/__tests__/otelMetadataProcessing.test.ts b/worker/src/queues/__tests__/otelMetadataProcessing.test.ts
index fa95249cce..d3b01b6b56 100644
--- a/worker/src/queues/__tests__/otelMetadataProcessing.test.ts
+++ b/worker/src/queues/__tests__/otelMetadataProcessing.test.ts
@@ -5,7 +5,10 @@
* NOTE: The dual-write path (otel-dual-write) uses mapKeys() in SQL which doesn't flatten.
*/
import { describe, it, expect, beforeEach, vi } from "vitest";
-import { OtelIngestionProcessor } from "@langfuse/shared/src/server";
+import {
+ metadataArraysToRecord,
+ OtelIngestionProcessor,
+} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { IngestionService } from "../../services/IngestionService";
import * as clickhouseWriterExports from "../../services/ClickhouseWriter";
@@ -121,17 +124,11 @@ async function processAndCreateEvent(
);
console.log("metadata_names:", JSON.stringify(eventRecord.metadata_names));
- console.log(
- "metadata_raw_values:",
- JSON.stringify(eventRecord.metadata_raw_values),
- );
- console.log("metadata:", JSON.stringify(eventRecord.metadata));
+ console.log("metadata_values:", JSON.stringify(eventRecord.metadata_values));
- const nameToValue = Object.fromEntries(
- eventRecord.metadata_names.map((name, i) => [
- name,
- eventRecord.metadata_raw_values[i],
- ]),
+ const nameToValue = metadataArraysToRecord(
+ eventRecord.metadata_names,
+ eventRecord.metadata_values,
);
return { eventRecord, nameToValue };
@@ -183,33 +180,4 @@ describe("OTel metadata processing", () => {
expect(nameToValue["scope.attributes"]).toBeUndefined();
});
});
-
- describe("json column", () => {
- it("stringifies nested objects in metadata JSON column", async () => {
- const { eventRecord } = await processAndCreateEvent(
- buildOtelSpan({
- scopeVersion: "4.0.0",
- resourceAttrKey: "service.name",
- resourceAttrValue: "svc-a",
- scopeAttrKey: "public_key",
- scopeAttrValue: "pk-test",
- metadataAttrs: [{ key: "env", value: { stringValue: "prod" } }],
- }),
- );
-
- // metadata JSON column stores stringified values (Record<string, string>)
- const meta = eventRecord.metadata;
- expect(meta.resourceAttributes).toBe(
- JSON.stringify({ "service.name": "svc-a" }),
- );
- expect(meta.scope).toBe(
- JSON.stringify({
- name: "langfuse-sdk",
- version: "4.0.0",
- attributes: { public_key: "pk-test" },
- }),
- );
- expect(meta.env).toBe("prod");
- });
- });
});
diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.ts
index 7149e3e4c4..90f747d566 100644
--- a/worker/src/services/ClickhouseWriter/index.ts
+++ b/worker/src/services/ClickhouseWriter/index.ts
@@ -46,7 +46,7 @@ export class ClickhouseWriter {
[TableName.ObservationsBatchStaging]: [],
[TableName.BlobStorageFileLog]: [],
[TableName.DatasetRunItems]: [],
- [TableName.Events]: [],
+ [TableName.EventsFull]: [],
};
this.start();
@@ -114,7 +114,7 @@ export class ClickhouseWriter {
this.flush(TableName.ObservationsBatchStaging, fullQueue),
this.flush(TableName.BlobStorageFileLog, fullQueue),
this.flush(TableName.DatasetRunItems, fullQueue),
- this.flush(TableName.Events, fullQueue),
+ this.flush(TableName.EventsFull, fullQueue),
]).catch((err) => {
logger.error("ClickhouseWriter.flushAll", err);
});
@@ -504,7 +504,7 @@ export enum TableName {
ObservationsBatchStaging = "observations_batch_staging",
BlobStorageFileLog = "blob_storage_file_log",
DatasetRunItems = "dataset_run_items_rmt",
- Events = "events",
+ EventsFull = "events_full", // Primary write target - MV auto-populates events_core
}
type RecordInsertType<T extends TableName> = T extends TableName.Scores
@@ -521,7 +521,7 @@ type RecordInsertType<T extends TableName> = T extends TableName.Scores
? BlobStorageFileLogInsertType
: T extends TableName.DatasetRunItems
? DatasetRunItemRecordInsertType
- : T extends TableName.Events
+ : T extends TableName.EventsFull
? EventRecordInsertType
: never;
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 4c08ebcf62..ffa9df2e28 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -345,9 +345,6 @@ export class IngestionService {
// Should not be required as convertValueToPlainJavascript() never returns null.
const metadataValues = flattened.values.map((v) => v ?? "");
- // Stringify metadata for the JSON column (Record<string, string>)
- const metadata = convertRecordValuesToString(eventData.metadata ?? {});
-
const eventRecord: EventRecordInsertType = {
// Required identifiers
id: eventData.spanId,
@@ -420,9 +417,8 @@ export class IngestionService {
output: eventData.output,
// Metadata
- metadata,
metadata_names: metadataNames,
- metadata_raw_values: metadataValues,
+ metadata_values: metadataValues,
// Source/instrumentation metadata
source: eventData.source,
@@ -465,13 +461,14 @@ export class IngestionService {
}
/**
- * Writes an event record directly to the events table.
+ * Writes an event record directly to the events_full table.
+ * A materialized view auto-populates events_core from events_full.
* Use createEventRecord() first to get the record, then call this to write.
*
* @param eventRecord - The event record to write
*/
public writeEventRecord(eventRecord: EventRecordInsertType): void {
- this.clickHouseWriter.addToQueue(TableName.Events, eventRecord);
+ this.clickHouseWriter.addToQueue(TableName.EventsFull, eventRecord);
}
private async processDatasetRunItemEventList(params: {