Skip to content

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

chore: create background migrations for traces amt tables (#7689)

Steffen Schmitz1f02e364e124
diff --git a/.env.dev-redis-cluster.example b/.env.dev-redis-cluster.example
index 5ef20c6eaf..77b1f5045a 100644
--- a/.env.dev-redis-cluster.example
+++ b/.env.dev-redis-cluster.example
@@ -82,3 +82,11 @@ ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# speeds up local development by not executing init scripts on server startup
NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
+
+# Use the following settings to enforce running the new AMTs during the tests
+LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES="true"
+LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES="true"
+LANGFUSE_EXPERIMENT_WHITELISTED_PROJECT_IDS="7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"
+LANGFUSE_EXPERIMENT_ADD_QUERY_RESULT_TO_SPAN_PROJECT_IDS="7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"
+LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT="true"
+LANGFUSE_EXPERIMENT_SAMPLING_RATE=1
\ No newline at end of file
diff --git a/packages/shared/clickhouse/migrations/clustered/0023_traces_aggregating_merge_trees.down.sql b/packages/shared/clickhouse/migrations/clustered/0023_traces_aggregating_merge_trees.down.sql
new file mode 100644
index 0000000000..61ab89c3f8
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0023_traces_aggregating_merge_trees.down.sql
@@ -0,0 +1,12 @@
+-- Drop materialized views first
+DROP VIEW IF EXISTS traces_30d_amt_mv ON CLUSTER default;
+DROP VIEW IF EXISTS traces_7d_amt_mv ON CLUSTER default;
+DROP VIEW IF EXISTS traces_all_amt_mv ON CLUSTER default;
+
+-- Drop AMT tables
+DROP TABLE IF EXISTS traces_30d_amt ON CLUSTER default;
+DROP TABLE IF EXISTS traces_7d_amt ON CLUSTER default;
+DROP TABLE IF EXISTS traces_all_amt ON CLUSTER default;
+
+-- Drop the Null table
+DROP TABLE IF EXISTS traces_null ON CLUSTER default;
diff --git a/packages/shared/clickhouse/migrations/clustered/0023_traces_aggregating_merge_trees.up.sql b/packages/shared/clickhouse/migrations/clustered/0023_traces_aggregating_merge_trees.up.sql
new file mode 100644
index 0000000000..fd243f4f6a
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0023_traces_aggregating_merge_trees.up.sql
@@ -0,0 +1,300 @@
+-- Create a Null table that serves as a trigger for all materialized views.
+-- We use a Null engine here to avoid storing intermediate results and save on storage.
+CREATE TABLE traces_null ON CLUSTER default
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `start_time` DateTime64(3),
+ `end_time` Nullable(DateTime64(3)),
+ `name` Nullable(String),
+
+ -- Metadata properties
+ `metadata` Map(LowCardinality(String), String),
+ `user_id` Nullable(String),
+ `session_id` Nullable(String),
+ `environment` String,
+ `tags` Array(String),
+ `version` Nullable(String),
+ `release` Nullable(String),
+
+ -- UI properties - We make them nullable to prevent absent values being interpreted as overwrites.
+ `bookmarked` Nullable(Bool),
+ `public` Nullable(Bool),
+
+ -- Aggregations -- DO NOT USE
+ `observation_ids` Array(String),
+ `score_ids` Array(String),
+ `cost_details` Map(String, Decimal64(12)),
+ `usage_details` Map(String, UInt64),
+ -- TODO: Do we want to aggregate/collect `levels` seen within the trace?
+
+ -- Input/Output
+ `input` String,
+ `output` String,
+
+ `created_at` DateTime64(3),
+ `updated_at` DateTime64(3),
+ `event_ts` DateTime64(3)
+) Engine = Null();
+
+-- Create the all AMT
+CREATE TABLE traces_all_amt ON CLUSTER default
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `timestamp` SimpleAggregateFunction(min, DateTime64(3)), -- Backward compatibility: redundant with start_time
+ `start_time` SimpleAggregateFunction(min, DateTime64(3)),
+ `end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- Metadata properties
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `environment` SimpleAggregateFunction(anyLast, String),
+ `tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- UI properties
+ `bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+ `public` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+
+ -- Aggregations -- DO NOT USE
+ `observation_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `score_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
+ `usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
+
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+
+ `created_at` SimpleAggregateFunction(min, DateTime64(3)),
+ `updated_at` SimpleAggregateFunction(max, DateTime64(3)),
+
+ -- Indexes
+ INDEX idx_trace_id id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
+) Engine = AggregatingMergeTree()
+ ORDER BY (project_id, id);
+
+-- Create materialized view for all_amt
+CREATE MATERIALIZED VIEW IF NOT EXISTS traces_all_amt_mv ON CLUSTER default TO traces_all_amt AS
+SELECT
+ -- Identifiers
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
+
+ -- Metadata properties
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
+
+ -- UI properties
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
+
+ -- Aggregations -- DO NOT USE
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
+
+ -- Input/Output
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
+
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
+GROUP BY project_id, id;
+
+-- Create the 7-day TTL AMT
+CREATE TABLE traces_7d_amt ON CLUSTER default
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `timestamp` SimpleAggregateFunction(min, DateTime64(3)), -- Backward compatibility: redundant with start_time
+ `start_time` SimpleAggregateFunction(min, DateTime64(3)),
+ `end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- Metadata properties
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `environment` SimpleAggregateFunction(anyLast, String),
+ `tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- UI properties
+ `bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+ `public` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+
+ -- Aggregations -- DO NOT USE
+ `observation_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `score_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
+ `usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
+
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+
+ `created_at` SimpleAggregateFunction(min, DateTime64(3)),
+ `updated_at` SimpleAggregateFunction(max, DateTime64(3)),
+
+ -- Indexes
+ INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
+) Engine = AggregatingMergeTree()
+ ORDER BY (project_id, id)
+ TTL toDate(start_time) + INTERVAL 7 DAY;
+
+-- Create materialized view for 7d_amt
+CREATE MATERIALIZED VIEW IF NOT EXISTS traces_7d_amt_mv ON CLUSTER default TO traces_7d_amt AS
+SELECT
+ -- Identifiers
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
+
+ -- Metadata properties
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
+
+ -- UI properties
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
+
+ -- Aggregations -- DO NOT USE
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
+
+ -- Input/Output
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
+
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
+GROUP BY project_id, id;
+
+-- Create the 30-day TTL AMT
+CREATE TABLE traces_30d_amt ON CLUSTER default
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `timestamp` SimpleAggregateFunction(min, DateTime64(3)), -- Backward compatibility: redundant with start_time
+ `start_time` SimpleAggregateFunction(min, DateTime64(3)),
+ `end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- Metadata properties
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `environment` SimpleAggregateFunction(anyLast, String),
+ `tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- UI properties
+ `bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+ `public` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+
+ -- Aggregations -- DO NOT USE
+ `observation_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `score_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
+ `usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
+
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+
+ `created_at` SimpleAggregateFunction(min, DateTime64(3)),
+ `updated_at` SimpleAggregateFunction(max, DateTime64(3)),
+
+ -- Indexes
+ INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
+) Engine = AggregatingMergeTree()
+ ORDER BY (project_id, id)
+ TTL toDate(start_time) + INTERVAL 30 DAY;
+
+-- Create materialized view for 30d_amt
+CREATE MATERIALIZED VIEW IF NOT EXISTS traces_30d_amt_mv ON CLUSTER default TO traces_30d_amt AS
+SELECT
+ -- Identifiers
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
+
+ -- Metadata properties
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
+
+ -- UI properties
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
+
+ -- Aggregations -- DO NOT USE
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
+
+ -- Input/Output
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
+
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
+GROUP BY project_id, id;
diff --git a/packages/shared/clickhouse/migrations/unclustered/0023_traces_aggregating_merge_trees.down.sql b/packages/shared/clickhouse/migrations/unclustered/0023_traces_aggregating_merge_trees.down.sql
new file mode 100644
index 0000000000..7042dec750
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0023_traces_aggregating_merge_trees.down.sql
@@ -0,0 +1,12 @@
+-- Drop materialized views first
+DROP VIEW IF EXISTS traces_30d_amt_mv;
+DROP VIEW IF EXISTS traces_7d_amt_mv;
+DROP VIEW IF EXISTS traces_all_amt_mv;
+
+-- Drop AMT tables
+DROP TABLE IF EXISTS traces_30d_amt;
+DROP TABLE IF EXISTS traces_7d_amt;
+DROP TABLE IF EXISTS traces_all_amt;
+
+-- Drop the Null table
+DROP TABLE IF EXISTS traces_null;
diff --git a/packages/shared/clickhouse/migrations/unclustered/0023_traces_aggregating_merge_trees.up.sql b/packages/shared/clickhouse/migrations/unclustered/0023_traces_aggregating_merge_trees.up.sql
new file mode 100644
index 0000000000..b9c91a50ba
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0023_traces_aggregating_merge_trees.up.sql
@@ -0,0 +1,300 @@
+-- Create a Null table that serves as a trigger for all materialized views.
+-- We use a Null engine here to avoid storing intermediate results and save on storage.
+CREATE TABLE traces_null
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `start_time` DateTime64(3),
+ `end_time` Nullable(DateTime64(3)),
+ `name` Nullable(String),
+
+ -- Metadata properties
+ `metadata` Map(LowCardinality(String), String),
+ `user_id` Nullable(String),
+ `session_id` Nullable(String),
+ `environment` String,
+ `tags` Array(String),
+ `version` Nullable(String),
+ `release` Nullable(String),
+
+ -- UI properties - We make them nullable to prevent absent values being interpreted as overwrites.
+ `bookmarked` Nullable(Bool),
+ `public` Nullable(Bool),
+
+ -- Aggregations
+ `observation_ids` Array(String),
+ `score_ids` Array(String),
+ `cost_details` Map(String, Decimal64(12)),
+ `usage_details` Map(String, UInt64),
+ -- TODO: Do we want to aggregate/collect `levels` seen within the trace?
+
+ -- Input/Output
+ `input` String,
+ `output` String,
+
+ `created_at` DateTime64(3),
+ `updated_at` DateTime64(3),
+ `event_ts` DateTime64(3)
+) Engine = Null();
+
+-- Create the all AMT
+CREATE TABLE traces_all_amt
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `timestamp` SimpleAggregateFunction(min, DateTime64(3)), -- Backward compatibility: redundant with start_time
+ `start_time` SimpleAggregateFunction(min, DateTime64(3)),
+ `end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- Metadata properties
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `environment` SimpleAggregateFunction(anyLast, String),
+ `tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- UI properties
+ `bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+ `public` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+
+ -- Aggregations
+ `observation_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `score_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
+ `usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
+
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+
+ `created_at` SimpleAggregateFunction(min, DateTime64(3)),
+ `updated_at` SimpleAggregateFunction(max, DateTime64(3)),
+
+ -- Indexes
+ INDEX idx_trace_id id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
+) Engine = AggregatingMergeTree()
+ ORDER BY (project_id, id);
+
+-- Create materialized view for all_amt
+CREATE MATERIALIZED VIEW IF NOT EXISTS traces_all_amt_mv TO traces_all_amt AS
+SELECT
+ -- Identifiers
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
+
+ -- Metadata properties
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
+
+ -- UI properties
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
+
+ -- Aggregations
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
+
+ -- Input/Output
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
+
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
+GROUP BY project_id, id;
+
+-- Create the 7-day TTL AMT
+CREATE TABLE traces_7d_amt
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `timestamp` SimpleAggregateFunction(min, DateTime64(3)), -- Backward compatibility: redundant with start_time
+ `start_time` SimpleAggregateFunction(min, DateTime64(3)),
+ `end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- Metadata properties
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `environment` SimpleAggregateFunction(anyLast, String),
+ `tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- UI properties
+ `bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+ `public` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+
+ -- Aggregations
+ `observation_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `score_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
+ `usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
+
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+
+ `created_at` SimpleAggregateFunction(min, DateTime64(3)),
+ `updated_at` SimpleAggregateFunction(max, DateTime64(3)),
+
+ -- Indexes
+ INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
+) Engine = AggregatingMergeTree()
+ ORDER BY (project_id, id)
+ TTL toDate(start_time) + INTERVAL 7 DAY;
+
+-- Create materialized view for 7d_amt
+CREATE MATERIALIZED VIEW IF NOT EXISTS traces_7d_amt_mv TO traces_7d_amt AS
+SELECT
+ -- Identifiers
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
+
+ -- Metadata properties
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
+
+ -- UI properties
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
+
+ -- Aggregations
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
+
+ -- Input/Output
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
+
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
+GROUP BY project_id, id;
+
+-- Create the 30-day TTL AMT
+CREATE TABLE traces_30d_amt
+(
+ -- Identifiers
+ `project_id` String,
+ `id` String,
+ `timestamp` SimpleAggregateFunction(min, DateTime64(3)), -- Backward compatibility: redundant with start_time
+ `start_time` SimpleAggregateFunction(min, DateTime64(3)),
+ `end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- Metadata properties
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `environment` SimpleAggregateFunction(anyLast, String),
+ `tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
+
+ -- UI properties
+ `bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+ `public` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
+
+ -- Aggregations
+ `observation_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `score_ids` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
+ `cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
+ `usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
+
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+
+ `created_at` SimpleAggregateFunction(min, DateTime64(3)),
+ `updated_at` SimpleAggregateFunction(max, DateTime64(3)),
+
+ -- Indexes
+ INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
+) Engine = AggregatingMergeTree()
+ ORDER BY (project_id, id)
+ TTL toDate(start_time) + INTERVAL 30 DAY;
+
+-- Create materialized view for 30d_amt
+CREATE MATERIALIZED VIEW IF NOT EXISTS traces_30d_amt_mv TO traces_30d_amt AS
+SELECT
+ -- Identifiers
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
+
+ -- Metadata properties
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
+
+ -- UI properties
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
+
+ -- Aggregations
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
+
+ -- Input/Output
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
+
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
+GROUP BY project_id, id;
\ No newline at end of file
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index 4566a3752b..da5ead416f 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -36,7 +36,7 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {
export async function upsertClickhouse<
T extends Record<string, unknown>,
>(opts: {
- table: "scores" | "traces" | "observations";
+ table: "scores" | "traces" | "observations" | "traces_null";
records: T[];
eventBodyMapper: (body: T) => Record<string, unknown>; // eslint-disable-line no-unused-vars
tags?: Record<string, string>;
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index 49862d9f78..eaba8564f7 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -122,7 +122,7 @@ export const traceRecordInsertSchema = traceRecordBaseSchema.extend({
});
export type TraceRecordInsertType = z.infer<typeof traceRecordInsertSchema>;
-export const traceMtRecordInsertSchema = z.object({
+export const traceNullRecordInsertSchema = z.object({
// Identifiers
project_id: z.string(),
id: z.string(),
@@ -157,7 +157,9 @@ export const traceMtRecordInsertSchema = z.object({
updated_at: z.number(),
event_ts: z.number(),
});
-export type TraceMtRecordInsertType = z.infer<typeof traceMtRecordInsertSchema>;
+export type TraceNullRecordInsertType = z.infer<
+ typeof traceNullRecordInsertSchema
+>;
export const scoreRecordBaseSchema = z.object({
id: z.string(),
@@ -495,9 +497,9 @@ export const convertPostgresScoreToInsert = (
};
};
-export const convertTraceToTraceMt = (
+export const convertTraceToTraceNull = (
traceRecord: TraceRecordInsertType,
-): TraceMtRecordInsertType => {
+): TraceNullRecordInsertType => {
return {
// Identifiers
project_id: traceRecord.project_id,
@@ -535,13 +537,13 @@ export const convertTraceToTraceMt = (
};
};
-export const convertObservationToTraceMt = (
+export const convertObservationToTraceNull = (
observationRecord: ObservationRecordInsertType,
-): TraceMtRecordInsertType => {
+): TraceNullRecordInsertType => {
return {
// Identifiers
project_id: observationRecord.project_id,
- // Use trace_id as the id in traces_mt. Always set given the conditions around calling the function
+ // Use trace_id as the id in traces_null. Always set given the conditions around calling the function
id: observationRecord.trace_id || "",
start_time: observationRecord.start_time,
end_time: observationRecord.end_time || null,
@@ -579,13 +581,13 @@ export const convertObservationToTraceMt = (
};
};
-export const convertScoreToTraceMt = (
+export const convertScoreToTraceNull = (
scoreRecord: ScoreRecordInsertType,
-): TraceMtRecordInsertType => {
+): TraceNullRecordInsertType => {
return {
// Identifiers
project_id: scoreRecord.project_id,
- // Use trace_id as the id in traces_mt. Always set given the conditions around calling the function
+ // Use trace_id as the id in traces_null. Always set given the conditions around calling the function
id: scoreRecord.trace_id || "",
start_time: scoreRecord.timestamp,
end_time: null, // scores don't have end_time
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index dde0500d1a..4f09e53591 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -15,12 +15,12 @@ import {
FilterList,
StringFilter,
} from "../queries/clickhouse-sql/clickhouse-filter";
-import { TraceRecordReadType, convertTraceToTraceMt } from "./definitions";
+import { TraceRecordReadType, convertTraceToTraceNull } from "./definitions";
import { tracesTableUiColumnDefinitions } from "../../tableDefinitions/mapTracesTable";
import { UiColumnMappings } from "../../tableDefinitions";
import {
- convertDateToClickhouseDateTime,
clickhouseClient,
+ convertDateToClickhouseDateTime,
} from "../clickhouse/client";
import { convertClickhouseToDomain } from "./traces_converters";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
@@ -204,7 +204,7 @@ export const checkTraceExists = async ({
t.project_id as project_id,
-- Add a timestamp alias to ensure we can filter on it
t.start_time as timestamp
- FROM ${traceAmt} t
+ FROM ${traceAmt} t FINAL
${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}
WHERE ${tracesFilterRes.query}
AND t.project_id = {projectId: String}
@@ -229,6 +229,7 @@ export const upsertTrace = async (trace: Partial<TraceRecordReadType>) => {
if (!["id", "project_id", "timestamp"].every((key) => key in trace)) {
throw new Error("Identifier fields must be provided to upsert Trace.");
}
+
await upsertClickhouse({
table: "traces",
records: [trace as TraceRecordReadType],
@@ -241,7 +242,7 @@ export const upsertTrace = async (trace: Partial<TraceRecordReadType>) => {
},
});
- // Also insert into traces_mt if experiment flag is enabled
+ // Also insert into traces_null if experiment flag is enabled
if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true") {
// Convert trace to insert format first (since we have read format)
const traceRecord = trace as TraceRecordReadType;
@@ -254,18 +255,18 @@ export const upsertTrace = async (trace: Partial<TraceRecordReadType>) => {
is_deleted: 0,
};
- // Convert to traces_mt format
- const traceMt = convertTraceToTraceMt(traceInsert);
+ // Convert to traces_null format
+ const traceNull = convertTraceToTraceNull(traceInsert);
- // Insert directly into traces_mt using clickhouse client
+ // Insert directly into traces_null using clickhouse client
await clickhouseClient().insert({
- table: "traces_mt",
+ table: "traces_null",
format: "JSONEachRow",
- values: [traceMt],
+ values: [traceNull],
clickhouse_settings: {
log_comment: JSON.stringify({
feature: "tracing",
- type: "trace_mt",
+ type: "traces_null",
kind: "upsert",
experiment: "insert_into_aggregating_merge_trees",
}),
@@ -1094,25 +1095,104 @@ export const getTracesIdentifierForSession = async (
};
export const deleteTraces = async (projectId: string, traceIds: string[]) => {
- const query = `
- DELETE FROM traces
- WHERE project_id = {projectId: String}
- AND id IN ({traceIds: Array(String)});
- `;
- await commandClickhouse({
- query: query,
- params: {
- projectId,
- traceIds,
+ await measureAndReturn({
+ operationName: "deleteTraces",
+ projectId,
+ input: {
+ params: {
+ projectId,
+ traceIds,
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "delete",
+ projectId,
+ },
},
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ existingExecution: async (input) => {
+ const query = `
+ DELETE FROM traces
+ WHERE project_id = {projectId: String}
+ AND id IN ({traceIds: Array(String)});
+ `;
+ await commandClickhouse({
+ query: query,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ });
},
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "delete",
- projectId,
+ newExecution: async (input) => {
+ await Promise.all([
+ // Delete from traces
+ await commandClickhouse({
+ query: `
+ DELETE FROM traces
+ WHERE project_id = {projectId: String}
+ AND id IN ({traceIds: Array(String)});
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_null
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_null
+ WHERE project_id = {projectId: String}
+ AND id IN ({traceIds: Array(String)});
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_all_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_all_amt
+ WHERE project_id = {projectId: String}
+ AND id IN ({traceIds: Array(String)});
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_7d_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_7d_amt
+ WHERE project_id = {projectId: String}
+ AND id IN ({traceIds: Array(String)});
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_30d_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_30d_amt
+ WHERE project_id = {projectId: String}
+ AND id IN ({traceIds: Array(String)});
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ ]);
},
});
};
@@ -1121,47 +1201,200 @@ export const deleteTracesOlderThanDays = async (
projectId: string,
beforeDate: Date,
) => {
- const query = `
- DELETE FROM traces
- WHERE project_id = {projectId: String}
- AND timestamp < {cutoffDate: DateTime64(3)};
- `;
- await commandClickhouse({
- query: query,
- params: {
- projectId,
- cutoffDate: convertDateToClickhouseDateTime(beforeDate),
+ await measureAndReturn({
+ operationName: "deleteTracesOlderThanDays",
+ projectId,
+ input: {
+ params: {
+ projectId,
+ cutoffDate: convertDateToClickhouseDateTime(beforeDate),
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "delete",
+ projectId,
+ },
},
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ existingExecution: async (input) => {
+ const query = `
+ DELETE FROM traces
+ WHERE project_id = {projectId: String}
+ AND timestamp < {cutoffDate: DateTime64(3)};
+ `;
+ await commandClickhouse({
+ query: query,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ });
},
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "delete",
- projectId,
+ newExecution: async (input) => {
+ await Promise.all([
+ // Delete from traces
+ await commandClickhouse({
+ query: `
+ DELETE FROM traces
+ WHERE project_id = {projectId: String}
+ AND timestamp < {cutoffDate: DateTime64(3)};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_null
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_null
+ WHERE project_id = {projectId: String}
+ AND start_time < {cutoffDate: DateTime64(3)};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_all_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_all_amt
+ WHERE project_id = {projectId: String}
+ AND start_time < {cutoffDate: DateTime64(3)};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_7d_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_7d_amt
+ WHERE project_id = {projectId: String}
+ AND start_time < {cutoffDate: DateTime64(3)};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_30d_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_30d_amt
+ WHERE project_id = {projectId: String}
+ AND start_time < {cutoffDate: DateTime64(3)};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ ]);
},
});
};
export const deleteTracesByProjectId = async (projectId: string) => {
- const query = `
- DELETE FROM traces
- WHERE project_id = {projectId: String};
- `;
- await commandClickhouse({
- query: query,
- params: {
- projectId,
+ await measureAndReturn({
+ operationName: "deleteTracesByProjectId",
+ projectId,
+ input: {
+ params: {
+ projectId,
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "delete",
+ projectId,
+ },
},
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ existingExecution: async (input) => {
+ const query = `
+ DELETE FROM traces
+ WHERE project_id = {projectId: String};
+ `;
+ await commandClickhouse({
+ query: query,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ });
},
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "delete",
- projectId,
+ newExecution: async (input) => {
+ await Promise.all([
+ // Delete from traces
+ await commandClickhouse({
+ query: `
+ DELETE FROM traces
+ WHERE project_id = {projectId: String};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_null
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_null
+ WHERE project_id = {projectId: String};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_all_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_all_amt
+ WHERE project_id = {projectId: String};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_7d_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_7d_amt
+ WHERE project_id = {projectId: String};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ // Delete from traces_30d_amt
+ commandClickhouse({
+ query: `
+ DELETE FROM traces_30d_amt
+ WHERE project_id = {projectId: String};
+ `,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ }),
+ ]);
},
});
};
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.ts
index 494601768c..590b6df43a 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -543,12 +543,8 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {
true,
);
- const defaultOrder = orderBy?.order && orderBy?.column === "timestamp";
const chOrderBy = orderByToClickhouseSql(
- [
- defaultOrder ? [{ column: "timestamp", order: orderBy.order }] : null,
- orderBy ?? null,
- ].flat(),
+ [orderBy ?? null].flat(),
tracesTableUiColumnDefinitions,
);
@@ -558,7 +554,7 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {
: getTimeframesTracesAMT(timeStampFilter?.value);
const query = `
- ${observationsAndScoresCTE}
+ ${observationsAndScoresCTE}
SELECT ${sqlSelect}
FROM ${tracesAmt} t FINAL
diff --git a/packages/shared/src/server/test-utils/clickhouse-helpers.ts b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
index 07038361f0..7efb0158b4 100644
--- a/packages/shared/src/server/test-utils/clickhouse-helpers.ts
+++ b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
@@ -4,7 +4,7 @@ import {
ObservationRecordInsertType,
ScoreRecordInsertType,
DatasetRunItemRecordInsertType,
- convertTraceToTraceMt,
+ convertTraceToTraceNull,
} from "../repositories/definitions";
import { env } from "../../env";
@@ -13,9 +13,9 @@ export const createTracesCh = async (trace: TraceRecordInsertType[]) => {
env.LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES === "true"
) {
await clickhouseClient().insert({
- table: "traces_mt",
+ table: "traces_null",
format: "JSONEachRow",
- values: trace.map(convertTraceToTraceMt),
+ values: trace.map(convertTraceToTraceNull),
});
}
return await clickhouseClient().insert({
diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.ts
index bef7c6e97f..c3e7a73d89 100644
--- a/web/src/__tests__/async/ingestion-api.servertest.ts
+++ b/web/src/__tests__/async/ingestion-api.servertest.ts
@@ -316,36 +316,40 @@ describe("/api/public/ingestion API Endpoint", () => {
"<",
"#",
"|",
- ])("should test special S3 characters in IDs (%s)", async (char: string) => {
- const traceId = randomUUID();
+ ])(
+ "should test special S3 characters in IDs (%s)",
+ async (char: string) => {
+ const traceId = randomUUID();
- const response = await makeAPICall("POST", "/api/public/ingestion", {
- batch: [
- {
- id: randomUUID(),
- type: "trace-create",
- timestamp: new Date().toISOString(),
- body: {
- id: `${traceId}-${char}-test`,
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [
+ {
+ id: randomUUID(),
+ type: "trace-create",
timestamp: new Date().toISOString(),
+ body: {
+ id: `${traceId}-${char}-test`,
+ timestamp: new Date().toISOString(),
+ },
},
- },
- ],
- });
+ ],
+ });
- expect(response.status).toBe(207);
+ expect(response.status).toBe(207);
- await waitForExpect(async () => {
- const trace = await getTraceById({
- traceId: `${traceId}-${char}-test`,
- projectId,
+ await waitForExpect(async () => {
+ const trace = await getTraceById({
+ traceId: `${traceId}-${char}-test`,
+ projectId,
+ });
+ expect(trace).toBeDefined();
+ expect(trace!.id).toBe(`${traceId}-${char}-test`);
+ expect(trace!.projectId).toBe(projectId);
+ expect(trace!.environment).toEqual("default");
});
- expect(trace).toBeDefined();
- expect(trace!.id).toBe(`${traceId}-${char}-test`);
- expect(trace!.projectId).toBe(projectId);
- expect(trace!.environment).toEqual("default");
- });
- });
+ },
+ 10000,
+ );
it("should fail for \\r in id", async () => {
const traceId = v4();
@@ -543,6 +547,7 @@ describe("/api/public/ingestion API Endpoint", () => {
);
});
},
+ 10000,
);
it.each([
@@ -630,6 +635,65 @@ describe("/api/public/ingestion API Endpoint", () => {
},
);
+ it("should merge metadata correctly across multiple trace updates", async () => {
+ const traceId = randomUUID();
+
+ // First update with initial metadata: {"step": 1, "status": "started"}
+ const traceUpdate1 = {
+ id: randomUUID(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "operation",
+ timestamp: new Date().toISOString(),
+ metadata: { step: 1, status: "started" },
+ },
+ };
+
+ const response1 = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [traceUpdate1],
+ });
+ expect(response1.status).toBe(207);
+
+ // Second update with additional metadata: {"step": 2, "error": ""}
+ // This should merge with the first update
+ const traceUpdate2 = {
+ id: randomUUID(),
+ type: "trace-create",
+ timestamp: new Date(Date.now() + 1000).toISOString(), // Later timestamp
+ body: {
+ id: traceId,
+ name: "operation",
+ timestamp: new Date(Date.now() + 1000).toISOString(),
+ metadata: { step: 2, error: "" },
+ },
+ };
+
+ const response2 = await makeAPICall("POST", "/api/public/ingestion", {
+ batch: [traceUpdate2],
+ });
+ expect(response2.status).toBe(207);
+
+ await waitForExpect(async () => {
+ const trace = await getTraceById({ traceId, projectId });
+ expect(trace).toBeDefined();
+ expect(trace!.id).toBe(traceId);
+ expect(trace!.projectId).toBe(projectId);
+
+ // Expected final metadata: {"step": 2, "status": "started", "error": ""}
+ // This verifies that:
+ // - "step" is updated to the latest value (2)
+ // - "status" is preserved from the first update ("started")
+ // - "error" is added from the second update ("")
+ expect(trace!.metadata).toEqual({
+ step: 2,
+ status: "started",
+ error: "",
+ });
+ });
+ }, 20000);
+
it("#4900: should clear score comment on update with `null`", async () => {
const scoreId = randomUUID();
const score1 = {
@@ -674,5 +738,5 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(score!.value).toEqual(100.5);
expect(score!.comment).toBe(null);
});
- });
+ }, 10000);
});
diff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/async/observations-api.servertest.ts
index 543b07b8f7..41549922dc 100644
--- a/web/src/__tests__/async/observations-api.servertest.ts
+++ b/web/src/__tests__/async/observations-api.servertest.ts
@@ -118,7 +118,7 @@ describe("/api/public/observations API Endpoint", () => {
eventType: "click",
target: "submit-button",
});
- }, 15_000);
+ }, 20_000);
it("should filter observations by level parameter", async () => {
const traceId = randomUUID();
diff --git a/web/src/__tests__/async/scores-api-v1.servertest.ts b/web/src/__tests__/async/scores-api-v1.servertest.ts
index 71cb82cd2d..ac437aba88 100644
--- a/web/src/__tests__/async/scores-api-v1.servertest.ts
+++ b/web/src/__tests__/async/scores-api-v1.servertest.ts
@@ -641,10 +641,9 @@ describe("/api/public/scores API Endpoint", () => {
totalPages: 1,
});
for (const val of getAllScore.body.data) {
- expect(val).toMatchObject({
- traceId: traceId,
- trace: { tags: ["prod", "test"], userId: "user-name" },
- });
+ expect(val.traceId).toBe(traceId);
+ expect(val.trace?.tags?.sort()).toEqual(["prod", "test"].sort());
+ expect(val.trace?.userId).toBe("user-name");
}
});
diff --git a/web/src/__tests__/async/scores-api-v2.servertest.ts b/web/src/__tests__/async/scores-api-v2.servertest.ts
index ea66dd5941..8ad1bf1f3e 100644
--- a/web/src/__tests__/async/scores-api-v2.servertest.ts
+++ b/web/src/__tests__/async/scores-api-v2.servertest.ts
@@ -475,10 +475,9 @@ describe("/api/public/v2/scores API Endpoint", () => {
totalPages: 1,
});
for (const val of getAllScore.body.data) {
- expect(val).toMatchObject({
- traceId: traceId,
- trace: { tags: ["prod", "test"], userId: "user-name" },
- });
+ expect(val.traceId).toBe(traceId);
+ expect(val.trace?.tags?.sort()).toEqual(["prod", "test"].sort());
+ expect(val.trace?.userId).toBe("user-name");
}
});
diff --git a/web/src/__tests__/async/traces-trpc.servertest.ts b/web/src/__tests__/async/traces-trpc.servertest.ts
index 8d3d2a063b..df303fd6e3 100644
--- a/web/src/__tests__/async/traces-trpc.servertest.ts
+++ b/web/src/__tests__/async/traces-trpc.servertest.ts
@@ -69,7 +69,7 @@ describe("traces trpc", () => {
expect(traceRes?.projectId).toEqual(projectId);
expect(traceRes?.name).toEqual(trace.name);
expect(traceRes?.timestamp).toEqual(new Date(trace.timestamp));
- expect(traceRes?.tags).toEqual(trace.tags);
+ expect(traceRes?.tags?.sort()).toEqual(trace.tags?.sort());
expect(traceRes?.input).toEqual(trace.input);
expect(traceRes?.output).toEqual(trace.output);
expect(traceRes?.userId).toEqual(trace.user_id);
diff --git a/web/src/__tests__/async/traces-ui-table.servertest.ts b/web/src/__tests__/async/traces-ui-table.servertest.ts
index 6520ad300a..2231c879a8 100644
--- a/web/src/__tests__/async/traces-ui-table.servertest.ts
+++ b/web/src/__tests__/async/traces-ui-table.servertest.ts
@@ -32,7 +32,7 @@ describe("Traces table API test", () => {
expect(tableRows).toHaveLength(1);
expect(tableRows[0].id).toEqual(trace_id);
expect(tableRows[0].projectId).toEqual(project_id);
- expect(tableRows[0].tags).toEqual(trace.tags);
+ expect(tableRows[0].tags.sort()).toEqual(trace.tags.sort());
expect(tableRows[0].name).toEqual(trace.name);
expect(tableRows[0].bookmarked).toEqual(trace.bookmarked);
expect(tableRows[0].release).toEqual(trace.release);
@@ -98,7 +98,7 @@ describe("Traces table API test", () => {
expect(tableRows).toHaveLength(1);
expect(tableRows[0].id).toEqual(trace_id);
expect(tableRows[0].projectId).toEqual(project_id);
- expect(tableRows[0].tags).toEqual(trace.tags);
+ expect(tableRows[0].tags.sort()).toEqual(trace.tags.sort());
expect(tableRows[0].name).toEqual(trace.name);
expect(tableRows[0].bookmarked).toEqual(trace.bookmarked);
expect(tableRows[0].release).toEqual(trace.release);
diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.ts
index 28f4088513..11828b57ec 100644
--- a/worker/src/__tests__/batchAction.test.ts
+++ b/worker/src/__tests__/batchAction.test.ts
@@ -46,7 +46,7 @@ describe("select all test suite", () => {
tableName: BatchExportTableName.Traces,
query: {
filter: [],
- orderBy: { column: "timestamp", order: "DESC" },
+ orderBy: { column: "id", order: "DESC" },
},
cutoffCreatedAt: new Date("2024-01-02"),
},
@@ -60,7 +60,7 @@ describe("select all test suite", () => {
tableName: BatchExportTableName.Traces,
cutoffCreatedAt: new Date("2024-01-02"),
filter: [],
- orderBy: { column: "timestamp", order: "DESC" },
+ orderBy: { column: "id", order: "DESC" },
});
const remainingRows: any[] = [];
@@ -76,7 +76,7 @@ describe("select all test suite", () => {
projectId: projectId,
cutoffCreatedAt: new Date("2024-01-02"),
filter: [],
- orderBy: { column: "timestamp", order: "DESC" },
+ orderBy: { column: "id", order: "DESC" },
exportLimit: 1000,
});
@@ -91,7 +91,7 @@ describe("select all test suite", () => {
expect(remainingRows2).toHaveLength(0);
expect(remainingRows).toHaveLength(0);
- });
+ }, 30000);
it("should handle filtered queries", async () => {
const { projectId } = await createOrgProjectAndApiKey();
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 374993d184..424f7f4b2d 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -729,6 +729,7 @@ describe("eval service tests", () => {
await upsertTrace({
id: traceId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "b",
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
diff --git a/worker/src/backgroundMigrations/migrateTracesToTracesAMTs.ts b/worker/src/backgroundMigrations/migrateTracesToTracesAMTs.ts
new file mode 100644
index 0000000000..59d92791c6
--- /dev/null
+++ b/worker/src/backgroundMigrations/migrateTracesToTracesAMTs.ts
@@ -0,0 +1,444 @@
+import { IBackgroundMigration } from "./IBackgroundMigration";
+import {
+ clickhouseClient,
+ ClickhouseClientType,
+ logger,
+} from "@langfuse/shared/src/server";
+import { parseArgs } from "node:util";
+import { prisma } from "@langfuse/shared/src/db";
+import { env } from "../env";
+import { randomUUID } from "node:crypto";
+
+// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table
+const backgroundMigrationId = "f4b51797-e5ae-4d74-9625-05321493486e";
+
+type MigrationState = {
+ maxDate: string | undefined;
+ minDate: string | undefined;
+ queryTimeoutMinutes: number | undefined;
+};
+
+/**
+ * Checks if a query exists in the system.query_log table
+ */
+async function checkQueryExists(
+ client: ClickhouseClientType,
+ queryId: string,
+): Promise<boolean> {
+ const queryLogTable =
+ env.CLICKHOUSE_CLUSTER_ENABLED === "true"
+ ? `clusterAllReplicas(${env.CLICKHOUSE_CLUSTER_NAME}, system.query_log)`
+ : "system.query_log";
+
+ const resultSet = await client.query({
+ query: `
+ SELECT COUNT(*) > 0 AS exists
+ FROM ${queryLogTable}
+ WHERE query_id = '${queryId}'
+ `,
+ format: "JSONEachRow",
+ });
+ const result = (await resultSet.json()) as { exists: 0 | 1 }[];
+ return result.length > 0 && result[0].exists !== 0;
+}
+
+/**
+ * Checks if a query has completed successfully
+ */
+async function checkCompletedQuery(
+ client: ClickhouseClientType,
+ queryId: string,
+): Promise<boolean> {
+ const queryLogTable =
+ env.CLICKHOUSE_CLUSTER_ENABLED === "true"
+ ? `clusterAllReplicas(${env.CLICKHOUSE_CLUSTER_NAME}, system.query_log)`
+ : "system.query_log";
+
+ const resultSet = await client.query({
+ query: `
+ SELECT type, exception
+ FROM ${queryLogTable}
+ WHERE query_id = '${queryId}' AND type != 'QueryStart'
+ LIMIT 1
+ `,
+ format: "JSONEachRow",
+ });
+ const result = (await resultSet.json()) as {
+ type: string;
+ exception: string | undefined;
+ }[];
+ if (result.length > 0 && result[0].type !== "QueryFinish") {
+ throw new Error(
+ `Query ${queryId} failed with ${result[0].type}: ${result[0].exception}`,
+ );
+ }
+ return result.length > 0;
+}
+
+/**
+ * Executes a long-running ClickHouse query with timeout and progress monitoring
+ * Based on: https://github.com/ClickHouse/clickhouse-js/blob/main/examples/long_running_queries_timeouts.ts#L85
+ */
+async function executeLongRunningQuery(
+ query: string,
+ timeoutMinutes: number,
+): Promise<void> {
+ const queryId = randomUUID();
+ const client = clickhouseClient();
+
+ const abortController = new AbortController();
+ const timeoutMs = timeoutMinutes * 60 * 1000;
+
+ logger.info(
+ `[Background Migration] Executing traces_null backfill query ${queryId}`,
+ );
+
+ // Start the query execution
+ const queryPromise = client.command({
+ query,
+ query_id: queryId,
+ abort_signal: abortController.signal,
+ });
+
+ const startTime = Date.now();
+
+ // Check whether the query was created
+ let checkExistTries = 0;
+ await new Promise<void>((resolve, reject) => {
+ const checkInterval = setInterval(async () => {
+ const queryExists = await checkQueryExists(client, queryId);
+ if (queryExists) {
+ clearInterval(checkInterval);
+ resolve();
+ }
+ // We rather use lots of tries, but a low interval to ensure that this completes quickly.
+ // Since the query should be cheap, we're not worried too much about the load.
+ if (checkExistTries++ > 60) {
+ clearInterval(checkInterval);
+ reject(
+ new Error(
+ `Query ${queryId} does not exist in system.query_log after ${
+ checkExistTries * 2
+ }s`,
+ ),
+ );
+ }
+ }, 2000);
+ });
+
+ // Cancel the HTTP request and keep it running server-side only.
+ abortController.abort();
+
+ // Handle the expected abort error when canceling the HTTP request
+ try {
+ await queryPromise;
+ } catch (err) {
+ if (err instanceof Error && err.message.includes("abort")) {
+ logger.info(
+ `[Background Migration] Query ${queryId} HTTP request aborted as expected, query continues server-side`,
+ );
+ } else {
+ throw err;
+ }
+ }
+
+ // Check whether the query completed or aborted after timeoutMin minutes
+ await new Promise<void>((resolve, reject) => {
+ const checkInterval = setInterval(async () => {
+ try {
+ const isCompleted = await checkCompletedQuery(client, queryId);
+ if (isCompleted) {
+ clearInterval(checkInterval);
+ resolve();
+ }
+ } catch (err) {
+ clearInterval(checkInterval);
+ reject(err);
+ }
+
+ // If Date.now() - startTime rounded down to a second is a multiple of 60, print a log message, i.e. ~ every minute
+ if (Math.floor((Date.now() - startTime) / 1000) % 60 === 0) {
+ logger.info(
+ `[Background Migration] Query ${queryId} still running after ${Math.floor(
+ (Date.now() - startTime) / 60000,
+ )} minutes`,
+ );
+ }
+
+ if (Date.now() - startTime > timeoutMs) {
+ logger.warn(
+ `[Background Migration] Query ${queryId} still running after ${timeoutMinutes} minutes. Aborting...`,
+ );
+ await client.command({
+ query: `KILL QUERY WHERE query_id = '${queryId}'`,
+ });
+ clearInterval(checkInterval);
+ reject(
+ new Error(
+ `Query ${queryId} cancelled after ${timeoutMinutes} minutes`,
+ ),
+ );
+ }
+ }, 1000);
+ });
+
+ logger.info(`[Background Migration] Query ${queryId} completed successfully`);
+}
+
+export default class MigrateTracesToTracesAMTs implements IBackgroundMigration {
+ private isAborted = false;
+ private isFinished = false;
+
+ async validate(
+ args: Record<string, unknown>,
+ attempts = 5,
+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {
+ // Check if Clickhouse credentials are configured
+ if (
+ !env.CLICKHOUSE_URL ||
+ !env.CLICKHOUSE_USER ||
+ !env.CLICKHOUSE_PASSWORD
+ ) {
+ return {
+ valid: false,
+ invalidReason:
+ "Clickhouse credentials must be configured to perform migration",
+ };
+ }
+
+ // Check if new ClickHouse tables exists
+ const tables = await clickhouseClient().query({
+ query: "SHOW TABLES",
+ });
+ const tableNames = (await tables.json()).data as { name: string }[];
+ if (
+ ["traces_null", "traces_all_amt", "traces_7d_amt", "traces_30_amt"].every(
+ (table) => tableNames.some((t) => t.name === table),
+ )
+ ) {
+ // Retry if the table does not exist as this may mean migrations are still pending
+ if (attempts > 0) {
+ logger.info(
+ `[Background Migration] ClickHouse tables do not exist. Expected to find traces_null, traces_all_amt, traces_7d_amt, traces_30_amt. Retrying in 10s...`,
+ );
+ return new Promise((resolve) => {
+ setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);
+ });
+ }
+ }
+
+ return { valid: true, invalidReason: undefined };
+ }
+
+ async run(args: Record<string, unknown>): Promise<void> {
+ const start = Date.now();
+ logger.info(
+ `[Background Migration] Migrating traces to traces AMTs with ${JSON.stringify(args)}`,
+ );
+
+ // @ts-ignore
+ const initialMigrationState: { state: MigrationState } =
+ await prisma.backgroundMigration.findUniqueOrThrow({
+ where: { id: backgroundMigrationId },
+ select: { state: true },
+ });
+
+ // Use values from database state if available, otherwise fall back to args
+ const queryTimeoutMinutes =
+ initialMigrationState.state?.queryTimeoutMinutes ??
+ (args.queryTimeoutMinutes as number | undefined);
+
+ const maxDate = initialMigrationState.state?.maxDate
+ ? new Date(initialMigrationState.state.maxDate)
+ : new Date((args.maxDate as string) ?? new Date());
+ const minDate = initialMigrationState.state?.minDate
+ ? new Date(initialMigrationState.state.minDate)
+ : new Date((args.minDate as string) ?? new Date("2023-05-18"));
+
+ await prisma.backgroundMigration.update({
+ where: { id: backgroundMigrationId },
+ data: {
+ state: {
+ maxDate,
+ minDate,
+ queryTimeoutMinutes,
+ },
+ },
+ });
+
+ while (!this.isAborted && !this.isFinished) {
+ const queryStart = Date.now();
+
+ // @ts-ignore
+ const migrationState: { state: { maxDate: string; minDate: string } } =
+ await prisma.backgroundMigration.findUniqueOrThrow({
+ where: { id: backgroundMigrationId },
+ select: { state: true },
+ });
+
+ const maxDate = new Date(migrationState.state.maxDate);
+ const minDate = new Date(migrationState.state.minDate);
+
+ // Get current month in YYYYMM format
+ const currentMonth = maxDate.toISOString().slice(0, 7).replace("-", "");
+ logger.info(
+ `[Background Migration] Migrating traces for ${currentMonth}`,
+ );
+
+ const query = `
+ INSERT INTO traces_null
+ SELECT
+ -- Identifiers
+ project_id,
+ id,
+ timestamp as start_time,
+ null as end_time,
+ name,
+
+ -- Metadata properties
+ metadata,
+ user_id,
+ session_id,
+ environment,
+ tags,
+ version,
+ release,
+
+ -- UI Properties
+ bookmarked,
+ public,
+
+ -- Aggregations (ignored)
+ [] as observation_ids,
+ [] as score_ids,
+ map() as cost_details,
+ map() as usage_details,
+
+ -- Input/Output
+ input,
+ output,
+
+ created_at,
+ updated_at,
+ event_ts
+ FROM traces
+ WHERE toYYYYMM(timestamp) = ${currentMonth}
+ `;
+
+ await executeLongRunningQuery(query, queryTimeoutMinutes ?? 90);
+
+ maxDate.setMonth(maxDate.getMonth() - 1);
+ await prisma.backgroundMigration.update({
+ where: { id: backgroundMigrationId },
+ data: {
+ state: {
+ ...migrationState.state,
+ maxDate,
+ },
+ },
+ });
+
+ logger.info(
+ `[Background Migration] Inserted traces into traces_null for ${currentMonth} in ${Date.now() - queryStart}ms`,
+ );
+
+ if (maxDate < minDate) {
+ logger.info(
+ "[Background Migration] No more traces to migrate. Exiting...",
+ );
+ this.isFinished = true;
+ }
+ }
+
+ if (this.isAborted) {
+ logger.info(
+ `[Background Migration] Migration of traces to traces AMTs aborted.`,
+ );
+ return;
+ }
+
+ logger.info(
+ `[Background Migration] Finished migration of traces to traces AMTs in ${Date.now() - start}ms`,
+ );
+ }
+
+ async abort(): Promise<void> {
+ logger.info(
+ `[Background Migration] Aborting migration of traces to traces AMTs`,
+ );
+ this.isAborted = true;
+ }
+}
+
+async function createBackgroundMigrationRecord(): Promise<void> {
+ logger.info("[Background Migration] Creating background migration record...");
+
+ await prisma.backgroundMigration.create({
+ data: {
+ id: backgroundMigrationId,
+ name: "20250704_1356_migrate_traces_to_traces_amt",
+ script: "migrateTracesToTracesAMTs",
+ args: {},
+ },
+ });
+ logger.info(
+ "[Background Migration] Background migration record created successfully",
+ );
+}
+
+// TODO: Confirm defaults for maxDate and minDate to ensure coverage for self-hosters
+async function main() {
+ const args = parseArgs({
+ options: {
+ maxDate: {
+ type: "string",
+ short: "d",
+ default: new Date().toISOString(),
+ },
+ minDate: {
+ type: "string",
+ short: "m",
+ default: new Date("2023-05-18T00:00:00.000Z").toISOString(),
+ },
+ createRecord: {
+ type: "boolean",
+ short: "c",
+ default: false,
+ },
+ timeoutMinutes: {
+ type: "string",
+ short: "t",
+ default: "90",
+ },
+ },
+ });
+
+ if (args.values.createRecord) {
+ await createBackgroundMigrationRecord();
+ }
+
+ // Convert string args to numbers
+ const migrationArgs = {
+ ...args.values,
+ queryTimeoutMinutes: parseInt(args.values.timeoutMinutes!),
+ };
+
+ const migration = new MigrateTracesToTracesAMTs();
+ await migration.validate(migrationArgs);
+ await migration.run(migrationArgs);
+}
+
+// If the script is being executed directly (not imported), run the main function
+if (require.main === module) {
+ main()
+ .then(() => {
+ process.exit(0);
+ })
+ .catch((error) => {
+ logger.error(
+ `[Background Migration] Migration execution failed: ${error}`,
+ error,
+ );
+ process.exit(1); // Exit with an error code
+ });
+}
diff --git a/worker/src/env.ts b/worker/src/env.ts
index f4a69c5b11..6188f42505 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -86,6 +86,7 @@ const EnvSchema = z.object({
CLICKHOUSE_CLUSTER_NAME: z.string().default("default"),
CLICKHOUSE_DB: z.string().default("default"),
CLICKHOUSE_PASSWORD: z.string(),
+ CLICKHOUSE_CLUSTER_ENABLED: z.enum(["true", "false"]).default("true"),
LANGFUSE_EVAL_CREATOR_WORKER_CONCURRENCY: z.coerce
.number()
.positive()
diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.ts
index b4ebe58c5a..292043b3df 100644
--- a/worker/src/services/ClickhouseWriter/index.ts
+++ b/worker/src/services/ClickhouseWriter/index.ts
@@ -9,7 +9,7 @@ import {
recordIncrement,
ScoreRecordInsertType,
TraceRecordInsertType,
- TraceMtRecordInsertType,
+ TraceNullRecordInsertType,
DatasetRunItemRecordInsertType,
} from "@langfuse/shared/src/server";
@@ -39,7 +39,7 @@ export class ClickhouseWriter {
this.queue = {
[TableName.Traces]: [],
- [TableName.TracesMt]: [],
+ [TableName.TracesNull]: [],
[TableName.Scores]: [],
[TableName.Observations]: [],
[TableName.BlobStorageFileLog]: [],
@@ -106,7 +106,7 @@ export class ClickhouseWriter {
recordIncrement("langfuse.queue.clickhouse_writer.request");
await Promise.all([
this.flush(TableName.Traces, fullQueue),
- this.flush(TableName.TracesMt, fullQueue),
+ this.flush(TableName.TracesNull, fullQueue),
this.flush(TableName.Scores, fullQueue),
this.flush(TableName.Observations, fullQueue),
this.flush(TableName.BlobStorageFileLog, fullQueue),
@@ -398,7 +398,7 @@ export class ClickhouseWriter {
export enum TableName {
Traces = "traces", // eslint-disable-line no-unused-vars
- TracesMt = "traces_mt", // eslint-disable-line no-unused-vars
+ TracesNull = "traces_null", // eslint-disable-line no-unused-vars
Scores = "scores", // eslint-disable-line no-unused-vars
Observations = "observations", // eslint-disable-line no-unused-vars
BlobStorageFileLog = "blob_storage_file_log", // eslint-disable-line no-unused-vars
@@ -411,8 +411,8 @@ type RecordInsertType<T extends TableName> = T extends TableName.Scores
? ObservationRecordInsertType
: T extends TableName.Traces
? TraceRecordInsertType
- : T extends TableName.TracesMt
- ? TraceMtRecordInsertType
+ : T extends TableName.TracesNull
+ ? TraceNullRecordInsertType
: T extends TableName.BlobStorageFileLog
? BlobStorageFileLogInsertType
: T extends TableName.DatasetRunItems
diff --git a/worker/src/services/IngestionService/README.md b/worker/src/services/IngestionService/README.md
index a77162caf9..3482349a6a 100644
--- a/worker/src/services/IngestionService/README.md
+++ b/worker/src/services/IngestionService/README.md
@@ -5,21 +5,23 @@
Warn: Do not apply on your own as this is highly experimental and may change anytime.
To reduce the costs associated with trace processing, we aim to derive trace information from spans eventually.
-As a first step, we create a new `traces_mt` table which acts as a proxy for a bunch of AggregatingMergeTrees that collapse
+As a first step, we created a `traces_mt` table which acted as a proxy for a bunch of AggregatingMergeTrees that collapse
trace writes into a single row.
-Eventually, we may move the `traces_mt` table to a `traces_null` table that doesn't store intermediate results.
+We have now moved to a `traces_null` table that doesn't store intermediate results to save on storage and compute overhead.
-We can enable experimental writes to the `traces_mt` table by setting `LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES=true`.
+We can enable experimental writes to the `traces_null` table by setting `LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES=true`.
This requires that the following table schema is manually applied on the database instance:
```sql
-- Setup
-- Context: https://fiddle.clickhouse.com/d4e84b88-6bd7-455c-9a84-e9126594f92a
--- Create a MergeTree table that serves as a trigger for all others.
--- We use a MergeTree here to track what was being inserted. Could be replaced
--- with a NULL table in future to save on storage.
-CREATE TABLE traces_mt
+
+-- TODO: Make sure to update migrateTracesToTracesAMTs.ts if the traces_null schema changes
+
+-- Create a Null table that serves as a trigger for all materialized views.
+-- We use a Null engine here to avoid storing intermediate results and save on storage.
+CREATE TABLE traces_null
(
-- Identifiers
`project_id` String,
@@ -55,9 +57,7 @@ CREATE TABLE traces_mt
`created_at` DateTime64(3),
`updated_at` DateTime64(3),
`event_ts` DateTime64(3)
-) Engine = MergeTree()
- ORDER BY (project_id, id)
- PARTITION BY toYYYYMM(start_time);
+) Engine = Null();
-- Create the all AMT
CREATE TABLE traces_all_amt
@@ -71,7 +71,7 @@ CREATE TABLE traces_all_amt
`name` SimpleAggregateFunction(anyLast, Nullable(String)),
-- Metadata properties
- `metadata` SimpleAggregateFunction(minMap, Map(String, String)),
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
`user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`environment` SimpleAggregateFunction(anyLast, String),
@@ -112,39 +112,39 @@ CREATE TABLE traces_all_amt
CREATE MATERIALIZED VIEW IF NOT EXISTS traces_all_amt_mv TO traces_all_amt AS
SELECT
-- Identifiers
- t0.project_id as project_id,
- t0.id as id,
- min(t0.start_time) as timestamp, -- Backward compatibility: redundant with start_time
- min(t0.start_time) as start_time,
- max(coalesce(t0.end_time, t0.start_time)) as end_time,
- anyLast(t0.name) as name,
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
-- Metadata properties
- minMap(t0.metadata) as metadata,
- anyLast(t0.user_id) as user_id,
- anyLast(t0.session_id) as session_id,
- anyLast(t0.environment) as environment,
- groupUniqArrayArray(t0.tags) as tags,
- anyLast(t0.version) as version,
- anyLast(t0.release) as release,
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
-- UI properties
- argMaxState(t0.bookmarked, if(t0.bookmarked is not null, t0.event_ts, toDateTime64(0, 3))) as bookmarked,
- argMaxState(t0.public, if(t0.public is not null, t0.event_ts, toDateTime64(0, 3))) as public,
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
-- Aggregations
- groupUniqArrayArray(t0.observation_ids) as observation_ids,
- groupUniqArrayArray(t0.score_ids) as score_ids,
- sumMap(t0.cost_details) as cost_details,
- sumMap(t0.usage_details) as usage_details,
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
-- Input/Output
- argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input,
- argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output,
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
- min(t0.created_at) as created_at,
- max(t0.updated_at) as updated_at
-FROM traces_mt t0
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
GROUP BY project_id, id;
-- Create the 7-day TTL AMT
@@ -159,7 +159,7 @@ CREATE TABLE traces_7d_amt
`name` SimpleAggregateFunction(anyLast, Nullable(String)),
-- Metadata properties
- `metadata` SimpleAggregateFunction(minMap, Map(String, String)),
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
`user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`environment` SimpleAggregateFunction(anyLast, String),
@@ -199,39 +199,39 @@ CREATE TABLE traces_7d_amt
CREATE MATERIALIZED VIEW IF NOT EXISTS traces_7d_amt_mv TO traces_7d_amt AS
SELECT
-- Identifiers
- t0.project_id as project_id,
- t0.id as id,
- min(t0.start_time) as timestamp, -- Backward compatibility: redundant with start_time
- min(t0.start_time) as start_time,
- max(coalesce(t0.end_time, t0.start_time)) as end_time,
- anyLast(t0.name) as name,
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
-- Metadata properties
- minMap(t0.metadata) as metadata,
- anyLast(t0.user_id) as user_id,
- anyLast(t0.session_id) as session_id,
- anyLast(t0.environment) as environment,
- groupUniqArrayArray(t0.tags) as tags,
- anyLast(t0.version) as version,
- anyLast(t0.release) as release,
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
-- UI properties
- argMaxState(t0.bookmarked, if(t0.bookmarked is not null, t0.event_ts, toDateTime64(0, 3))) as bookmarked,
- argMaxState(t0.public, if(t0.public is not null, t0.event_ts, toDateTime64(0, 3))) as public,
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
-- Aggregations
- groupUniqArrayArray(t0.observation_ids) as observation_ids,
- groupUniqArrayArray(t0.score_ids) as score_ids,
- sumMap(t0.cost_details) as cost_details,
- sumMap(t0.usage_details) as usage_details,
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
-- Input/Output
- argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input,
- argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output,
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
- min(t0.created_at) as created_at,
- max(t0.updated_at) as updated_at
-FROM traces_mt t0
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
GROUP BY project_id, id;
-- Create the 30-day TTL AMT
@@ -246,7 +246,7 @@ CREATE TABLE traces_30d_amt
`name` SimpleAggregateFunction(anyLast, Nullable(String)),
-- Metadata properties
- `metadata` SimpleAggregateFunction(minMap, Map(String, String)),
+ `metadata` SimpleAggregateFunction(maxMap, Map(String, String)),
`user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`environment` SimpleAggregateFunction(anyLast, String),
@@ -286,39 +286,39 @@ CREATE TABLE traces_30d_amt
CREATE MATERIALIZED VIEW IF NOT EXISTS traces_30d_amt_mv TO traces_30d_amt AS
SELECT
-- Identifiers
- t0.project_id as project_id,
- t0.id as id,
- min(t0.start_time) as timestamp, -- Backward compatibility: redundant with start_time
- min(t0.start_time) as start_time,
- max(coalesce(t0.end_time, t0.start_time)) as end_time,
- anyLast(t0.name) as name,
+ tn.project_id as project_id,
+ tn.id as id,
+ min(tn.start_time) as timestamp, -- Backward compatibility: redundant with start_time
+ min(tn.start_time) as start_time,
+ max(coalesce(tn.end_time, tn.start_time)) as end_time,
+ anyLast(tn.name) as name,
-- Metadata properties
- minMap(t0.metadata) as metadata,
- anyLast(t0.user_id) as user_id,
- anyLast(t0.session_id) as session_id,
- anyLast(t0.environment) as environment,
- groupUniqArrayArray(t0.tags) as tags,
- anyLast(t0.version) as version,
- anyLast(t0.release) as release,
+ maxMap(tn.metadata) as metadata,
+ anyLast(tn.user_id) as user_id,
+ anyLast(tn.session_id) as session_id,
+ anyLast(tn.environment) as environment,
+ groupUniqArrayArray(tn.tags) as tags,
+ anyLast(tn.version) as version,
+ anyLast(tn.release) as release,
-- UI properties
- argMaxState(t0.bookmarked, if(t0.bookmarked is not null, t0.event_ts, toDateTime64(0, 3))) as bookmarked,
- argMaxState(t0.public, if(t0.public is not null, t0.event_ts, toDateTime64(0, 3))) as public,
+ argMaxState(tn.bookmarked, if(tn.bookmarked is not null, tn.event_ts, toDateTime64(0, 3))) as bookmarked,
+ argMaxState(tn.public, if(tn.public is not null, tn.event_ts, toDateTime64(0, 3))) as public,
-- Aggregations
- groupUniqArrayArray(t0.observation_ids) as observation_ids,
- groupUniqArrayArray(t0.score_ids) as score_ids,
- sumMap(t0.cost_details) as cost_details,
- sumMap(t0.usage_details) as usage_details,
+ groupUniqArrayArray(tn.observation_ids) as observation_ids,
+ groupUniqArrayArray(tn.score_ids) as score_ids,
+ sumMap(tn.cost_details) as cost_details,
+ sumMap(tn.usage_details) as usage_details,
-- Input/Output
- argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input,
- argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output,
+ argMaxState(tn.input, if(tn.input <> '', tn.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(tn.output, if(tn.output <> '', tn.event_ts, toDateTime64(0, 3))) as output,
- min(t0.created_at) as created_at,
- max(t0.updated_at) as updated_at
-FROM traces_mt t0
+ min(tn.created_at) as created_at,
+ max(tn.updated_at) as updated_at
+FROM traces_null tn
GROUP BY project_id, id;
```
@@ -400,20 +400,28 @@ WITH amt_data AS (
-- Main query to compare AMT with original traces table
SELECT t.project_id,
t.id,
- -- Identify differences between tables
- t.timestamp != a.start_time AS timestamp_diff,
- t.name != a.name AS name_diff,
- t.user_id != a.user_id AS user_id_diff,
- t.session_id != a.session_id AS session_id_diff,
- t.release != a.release AS release_diff,
- t.version != a.version AS version_diff,
- t.public != a.public_value AS public_diff,
- t.bookmarked != a.bookmarked_value AS bookmarked_diff,
- arraySort(t.tags) != arraySort(a.tags) AS tags_diff,
- t.input != a.input_value AS input_diff,
- t.output != a.output_value AS output_diff,
- t.metadata != a.metadata AS metadata_diff,
- t.environment != a.environment AS environment_diff,
+ -- Null-safe difference detection
+ NOT (t.timestamp = a.start_time OR (t.timestamp IS NULL AND a.start_time IS NULL)) AS timestamp_diff,
+ NOT (t.name = a.name OR (t.name IS NULL AND a.name IS NULL)) AS name_diff,
+ NOT (t.user_id = a.user_id OR (t.user_id IS NULL AND a.user_id IS NULL)) AS user_id_diff,
+ NOT (t.session_id = a.session_id OR (t.session_id IS NULL AND a.session_id IS NULL)) AS session_id_diff,
+ NOT (t.release = a.release OR (t.release IS NULL AND a.release IS NULL)) AS release_diff,
+ NOT (t.version = a.version OR (t.version IS NULL AND a.version IS NULL)) AS version_diff,
+ NOT (t.public = a.public_value OR (t.public IS NULL AND a.public_value IS NULL)) AS public_diff,
+ NOT (t.bookmarked = a.bookmarked_value OR (t.bookmarked IS NULL AND a.bookmarked_value IS NULL)) AS bookmarked_diff,
+ NOT (arraySort(t.tags) = arraySort(a.tags) OR (t.tags IS NULL AND a.tags IS NULL)) AS tags_diff,
+ NOT (t.input = a.input_value OR (t.input IS NULL AND a.input_value IS NULL)) AS input_diff,
+ NOT (t.output = a.output_value OR (t.output IS NULL AND a.output_value IS NULL)) AS output_diff,
+ -- Order-independent metadata comparison
+ NOT (
+ -- Check if both are null
+ (t.metadata IS NULL AND a.metadata IS NULL) OR
+ -- Check if both have same keys and values
+ (t.metadata IS NOT NULL AND a.metadata IS NOT NULL AND
+ arraySort(mapKeys(t.metadata)) = arraySort(mapKeys(a.metadata)) AND
+ arrayAll(k -> t.metadata[k] = a.metadata[k], mapKeys(t.metadata)))
+ ) AS metadata_diff,
+ NOT (t.environment = a.environment OR (t.environment IS NULL AND a.environment IS NULL)) AS environment_diff,
-- Include original values for comparison
t.timestamp AS traces_timestamp,
@@ -533,6 +541,11 @@ We could use an opt-in on a projectId basis.
- [x] **getTracesByIdsForAnyProject()** - `packages/shared/src/server/repositories/traces.ts:1115-1141`
-### 8. Writes
+### 8. Delete Operations
+- [x] **deleteTraces()** - `packages/shared/src/server/repositories/traces.ts:790++`
+- [x] **deleteTracesOlderThanDays()** - `packages/shared/src/server/repositories/traces.ts:814++`
+- [x] **deleteTracesByProjectId()** - `packages/shared/src/server/repositories/traces.ts:841++`
-- [ ] **upsertTrace()** - `packages/shared/src/server/repositories/traces.ts:224`
+### 9. Writes
+
+- [x] **upsertTrace()** - `packages/shared/src/server/repositories/traces.ts:224`
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index fc44c8991a..e40ed286ab 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -32,9 +32,9 @@ import {
UsageCostType,
findModel,
validateAndInflateScore,
- convertObservationToTraceMt,
- convertTraceToTraceMt,
- convertScoreToTraceMt,
+ convertObservationToTraceNull,
+ convertTraceToTraceNull,
+ convertScoreToTraceNull,
DatasetRunItemRecordInsertType,
} from "@langfuse/shared/src/server";
@@ -348,8 +348,8 @@ export class IngestionService {
env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true" &&
finalScoreRecord.trace_id
) {
- const traceMtRecord = convertScoreToTraceMt(finalScoreRecord);
- this.clickHouseWriter.addToQueue(TableName.TracesMt, traceMtRecord);
+ const traceNullRecord = convertScoreToTraceNull(finalScoreRecord);
+ this.clickHouseWriter.addToQueue(TableName.TracesNull, traceNullRecord);
}
}
@@ -441,13 +441,13 @@ export class IngestionService {
this.clickHouseWriter.addToQueue(TableName.Traces, finalTraceRecord);
- // Experimental: Also write to traces_mt table if experiment flag is enabled
+ // Experimental: Also write to traces_null table if experiment flag is enabled
// Here we use the raw events to ensure that we stop relying on the merge logic
if (
env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true"
) {
- traceRecords.map(convertTraceToTraceMt).forEach((r) =>
- this.clickHouseWriter.addToQueue(TableName.TracesMt, {
+ traceRecords.map(convertTraceToTraceNull).forEach((r) =>
+ this.clickHouseWriter.addToQueue(TableName.TracesNull, {
...r,
// We need to re-add input and output here as they were excluded in a previous mapping step
input: finalTraceRecord.input ?? "",
@@ -587,8 +587,10 @@ export class IngestionService {
env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true" &&
finalObservationRecord.trace_id
) {
- const traceMtRecord = convertObservationToTraceMt(finalObservationRecord);
- this.clickHouseWriter.addToQueue(TableName.TracesMt, traceMtRecord);
+ const traceNullRecord = convertObservationToTraceNull(
+ finalObservationRecord,
+ );
+ this.clickHouseWriter.addToQueue(TableName.TracesNull, traceNullRecord);
}
}
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 490a4fd0ef..0469061093 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -2151,7 +2151,7 @@ async function getClickhouseRecord<T extends TableName>(
return (
tableName === TableName.Traces
? traceRecordReadSchema.parse(result)
- : tableName === TableName.TracesMt
+ : tableName === TableName.TracesNull
? traceRecordReadSchema.parse(result)
: tableName === TableName.Observations
? observationRecordReadSchema.parse(result)