🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(v4): promote events tables to CH migration and flip v4 env defaults (#14812)
Steffen Schmitzeaa34c3e7fd8
diff --git a/.env.dev-azure.example b/.env.dev-azure.exampleindex d84c398d06..c3381ce97d 100644--- a/.env.dev-azure.example+++ b/.env.dev-azure.example@@ -84,3 +84,17 @@ ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000# speeds up local development by not executing init scripts on server startupNEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"++# V4 migration flags. Pinned to dual write mode to ensure we cover the tests.+# Write target: `legacy` | `dual` | `events_only`.+LANGFUSE_MIGRATION_V4_WRITE_MODE=dual+# Gate the V4 events_full read paths (UI, tRPC, v2 APIs, observations API).+# Self-hosted `dual` deployments must set this to `true` to offer users the V4+# preview toggle; with `dual` + `false` the preview stays unavailable to users.+LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true+# OTel ingestion behaviour: `dual_write` (SDK-version dispatch) or `direct`.+LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write+# Keep the WIP historic backfill dormant for local dev / CI. The v4 code default+# is `true`, but the general test suite should not run the backfill underneath it+# (it has a dedicated e2e spec). Set to `true` to exercise the backfill locally.+LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL=falsediff --git a/.env.dev-oci.example b/.env.dev-oci.exampleindex 590c7c14d3..8b8ff7fb7a 100644--- a/.env.dev-oci.example+++ b/.env.dev-oci.example@@ -194,3 +194,17 @@ OCI_CONFIG_PROFILE=DEFAULT# - If downloads work inside the cluster but not externally, configure# LANGFUSE_S3_BATCH_EXPORT_EXTERNAL_ENDPOINT to a publicly reachable endpoint/DNS.#####################################################################++# V4 migration flags. Pinned to dual write mode to ensure we cover the tests.+# Write target: `legacy` | `dual` | `events_only`.+LANGFUSE_MIGRATION_V4_WRITE_MODE=dual+# Gate the V4 events_full read paths (UI, tRPC, v2 APIs, observations API).+# Self-hosted `dual` deployments must set this to `true` to offer users the V4+# preview toggle; with `dual` + `false` the preview stays unavailable to users.+LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true+# OTel ingestion behaviour: `dual_write` (SDK-version dispatch) or `direct`.+LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write+# Keep the WIP historic backfill dormant for local dev / CI. The v4 code default+# is `true`, but the general test suite should not run the backfill underneath it+# (it has a dedicated e2e spec). Set to `true` to exercise the backfill locally.+LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL=falsediff --git a/.env.dev-redis-cluster.example b/.env.dev-redis-cluster.exampleindex d306cc458c..2a98da0beb 100644--- a/.env.dev-redis-cluster.example+++ b/.env.dev-redis-cluster.example@@ -93,3 +93,17 @@ ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000# speeds up local development by not executing init scripts on server startupNEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"++# V4 migration flags. Pinned to dual write mode to ensure we cover the tests.+# Write target: `legacy` | `dual` | `events_only`.+LANGFUSE_MIGRATION_V4_WRITE_MODE=dual+# Gate the V4 events_full read paths (UI, tRPC, v2 APIs, observations API).+# Self-hosted `dual` deployments must set this to `true` to offer users the V4+# preview toggle; with `dual` + `false` the preview stays unavailable to users.+LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true+# OTel ingestion behaviour: `dual_write` (SDK-version dispatch) or `direct`.+LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write+# Keep the WIP historic backfill dormant for local dev / CI. The v4 code default+# is `true`, but the general test suite should not run the backfill underneath it+# (it has a dedicated e2e spec). Set to `true` to exercise the backfill locally.+LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL=falsediff --git a/.env.dev.example b/.env.dev.exampleindex 6b0bc2fddb..2bf28c53ac 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -207,7 +207,8 @@ LANGFUSE_IN_APP_AGENT_AWS_PROFILE="playground"# Optional: overrides Lambda's default INTERNET_EGRESS connector.# LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EGRESS_NETWORK_CONNECTOR_ARN="arn:aws:lambda:us-east-1:123456789012:network-connector:langfuse-in-app-agent-sandbox-egress"-# V4 migration flags.+# V4 migration flags. Pinned to dual write mode to ensure we cover the tests;+# bare deployments get the flipped v4 code defaults (events_only / direct).# Write target: `legacy` | `dual` | `events_only`.LANGFUSE_MIGRATION_V4_WRITE_MODE=dual# Gate the V4 events_full read paths (UI, tRPC, v2 APIs, observations API).@@ -216,6 +217,10 @@ LANGFUSE_MIGRATION_V4_WRITE_MODE=dualLANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN=true# OTel ingestion behaviour: `dual_write` (SDK-version dispatch) or `direct`.LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write+# Keep the WIP historic backfill dormant for local dev / CI. The v4 code default+# is `true`, but the general test suite should not run the backfill underneath it+# (it has a dedicated e2e spec). Set to `true` to exercise the backfill locally.+LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL=false# Legacy tracing UI controlsLANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH=falsediff --git a/docker-compose.dev-azure.yml b/docker-compose.dev-azure.ymlindex 7e3acc2be5..449835b377 100644--- a/docker-compose.dev-azure.yml+++ b/docker-compose.dev-azure.yml@@ -1,6 +1,6 @@services:clickhouse:- image: docker.io/clickhouse/clickhouse-server:24.3+ image: docker.io/clickhouse/clickhouse-server:25.12user: "101:101"environment:CLICKHOUSE_DB: defaultdiff --git a/docker-compose.dev-redis-cluster.yml b/docker-compose.dev-redis-cluster.ymlindex e70bcbbc9d..c8561a6fbd 100644--- a/docker-compose.dev-redis-cluster.yml+++ b/docker-compose.dev-redis-cluster.yml@@ -12,7 +12,7 @@ x-redis-cluster-healthcheck: &redis-cluster-healthcheckservices:clickhouse:- image: docker.io/clickhouse/clickhouse-server:24.3+ image: docker.io/clickhouse/clickhouse-server:25.12user: "101:101"environment:CLICKHOUSE_DB: defaultdiff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 02b3178d65..a861e60213 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -1,7 +1,8 @@services:clickhouse:- # Upgrade from 24.3 to check behaviour on new events table.- # Unit tests still verify 24.3 behaviour using -azure and -redis-cluster configs.+ # ClickHouse 25.12 is the Langfuse v4 minimum (events tables require the+ # >=25.x text indexes / enable_full_text_index). All dev and CI deploy-mode+ # configs pin the same version.image: docker.io/clickhouse/clickhouse-server:25.12user: "101:101"container_name: ${CLICKHOUSE_CONTAINER_NAME:-langfuse-clickhouse}diff --git a/packages/shared/clickhouse/migrations/clustered/0038_create_observations_batch_staging.down.sql b/packages/shared/clickhouse/migrations/clustered/0038_create_observations_batch_staging.down.sqlnew file mode 100644index 0000000000..e3177579f2--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0038_create_observations_batch_staging.down.sql@@ -0,0 +1,5 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- table may predate this migration (created via dev-tables.sh on v4 preview+-- deployments) and may hold production-grade event data. Rolling back drops+-- that data regardless of which path created the table.+DROP TABLE IF EXISTS observations_batch_staging ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/clustered/0038_create_observations_batch_staging.up.sql b/packages/shared/clickhouse/migrations/clustered/0038_create_observations_batch_staging.up.sqlnew file mode 100644index 0000000000..c43b1a8209--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0038_create_observations_batch_staging.up.sql@@ -0,0 +1,51 @@+CREATE TABLE IF NOT EXISTS observations_batch_staging ON CLUSTER default+(+ id String,+ trace_id String,+ project_id String,+ type LowCardinality(String),+ parent_observation_id Nullable(String),+ start_time DateTime64(3),+ end_time Nullable(DateTime64(3)),+ name String,+ metadata Map(LowCardinality(String), String),+ level LowCardinality(String),+ status_message Nullable(String),+ version Nullable(String),+ input Nullable(String) CODEC(ZSTD(3)),+ output Nullable(String) CODEC(ZSTD(3)),+ provided_model_name Nullable(String),+ internal_model_id Nullable(String),+ model_parameters Nullable(String),+ provided_usage_details Map(LowCardinality(String), UInt64),+ usage_details Map(LowCardinality(String), UInt64),+ provided_cost_details Map(LowCardinality(String), Decimal64(12)),+ cost_details Map(LowCardinality(String), Decimal64(12)),+ total_cost Nullable(Decimal64(12)),+ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),+ tool_definitions Map(String, String),+ tool_calls Array(String),+ tool_call_names Array(String),+ completion_start_time Nullable(DateTime64(3)),+ prompt_id Nullable(String),+ prompt_name Nullable(String),+ prompt_version Nullable(UInt16),+ created_at DateTime64(3) DEFAULT now(),+ updated_at DateTime64(3) DEFAULT now(),+ event_ts DateTime64(3),+ is_deleted UInt8,+ s3_first_seen_timestamp DateTime64(3),+ environment LowCardinality(String) DEFAULT 'default'+)+ENGINE = ReplicatedReplacingMergeTree(event_ts, is_deleted)+PARTITION BY toStartOfInterval(s3_first_seen_timestamp, INTERVAL 3 MINUTE)+PRIMARY KEY (project_id, toDate(s3_first_seen_timestamp))+ORDER BY (+ project_id,+ toDate(s3_first_seen_timestamp),+ trace_id,+ id+)+TTL toDateTime(s3_first_seen_timestamp) + INTERVAL 48 HOUR+SETTINGS ttl_only_drop_parts = 1;diff --git a/packages/shared/clickhouse/migrations/clustered/0039_create_events_full.down.sql b/packages/shared/clickhouse/migrations/clustered/0039_create_events_full.down.sqlnew file mode 100644index 0000000000..3b3ae1aa49--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0039_create_events_full.down.sql@@ -0,0 +1,5 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- table may predate this migration (created via dev-tables.sh on v4 preview+-- deployments) and may hold production-grade event data. Rolling back drops+-- that data regardless of which path created the table.+DROP TABLE IF EXISTS events_full ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/clustered/0039_create_events_full.up.sql b/packages/shared/clickhouse/migrations/clustered/0039_create_events_full.up.sqlnew file mode 100644index 0000000000..9e8a743590--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0039_create_events_full.up.sql@@ -0,0 +1,124 @@+CREATE TABLE IF NOT EXISTS events_full ON CLUSTER default+(+ project_id String,+ trace_id String,+ span_id String,+ parent_span_id String,++ start_time DateTime64(6),+ end_time Nullable(DateTime64(6)),++ -- Core properties+ name String,+ type LowCardinality(String),+ environment LowCardinality(String) DEFAULT 'default',+ version String,+ release String,+ trace_name String,+ user_id String,+ session_id String,+ tags Array(String),+ level LowCardinality(String),+ status_message String,+ completion_start_time Nullable(DateTime64(6)),+ is_app_root Bool DEFAULT false,++ -- Updateable properties+ bookmarked Bool DEFAULT false,+ public Bool DEFAULT false,++ -- Prompt+ prompt_id String,+ prompt_name String,+ prompt_version Nullable(UInt16),++ -- Model+ model_id String,+ provided_model_name String,+ model_parameters String,++ -- Usage and Cost+ provided_usage_details Map(LowCardinality(String), UInt64),+ usage_details Map(LowCardinality(String), UInt64),+ provided_cost_details Map(LowCardinality(String), Decimal(18,12)),+ cost_details Map(LowCardinality(String), Decimal(18,12)),+ calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),+ calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ total_cost Decimal(18, 12) ALIAS cost_details['total'],++ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),++ -- Tools+ tool_definitions Map(String, String),+ tool_calls Array(String),+ tool_call_names Array(String),++ -- I/O+ input String CODEC(ZSTD(3)),+ input_length UInt64 MATERIALIZED lengthUTF8(input),+ output String CODEC(ZSTD(3)),+ output_length UInt64 MATERIALIZED lengthUTF8(output),++ -- Metadata+ metadata_names Array(String),+ metadata_values Array(String),++ -- Experiment properties+ experiment_id String,+ experiment_name String,+ experiment_metadata_names Array(String),+ experiment_metadata_values Array(String),+ experiment_description String,+ experiment_dataset_id String,+ experiment_item_id String,+ experiment_item_version Nullable(DateTime64(6)),+ experiment_item_expected_output String,+ experiment_item_metadata_names Array(String),+ experiment_item_metadata_values Array(String),+ experiment_item_root_span_id String,++ -- Source metadata (Instrumentation)+ source LowCardinality(String),+ service_name String,+ service_version String,+ scope_name String,+ scope_version String,+ telemetry_sdk_language LowCardinality(String),+ telemetry_sdk_name String,+ telemetry_sdk_version String,++ -- Generic props+ blob_storage_file_path String,+ event_bytes UInt64,+ created_at DateTime64(6) DEFAULT now(),+ updated_at DateTime64(6) DEFAULT now(),+ event_ts DateTime64(6),+ is_deleted UInt8,++ -- Indexes+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,+ INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,+ INDEX idx_fts_input_low lower(input) TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_output_low lower(output) TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha)+)+ENGINE = ReplicatedReplacingMergeTree(event_ts, is_deleted)+PARTITION BY toYYYYMM(start_time)+PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))+ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)+SAMPLE BY xxHash32(trace_id)+SETTINGS+ index_granularity_bytes = '64Mi', -- Default 10MiB. Prevents very small granules due to large rows.+ merge_max_block_size_bytes = '64Mi',+ enable_block_number_column = 1,+ enable_block_offset_column = 1,+ prewarm_mark_cache = 1,+ prewarm_primary_key_cache = 1,+ enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/clustered/0040_create_events_core.down.sql b/packages/shared/clickhouse/migrations/clustered/0040_create_events_core.down.sqlnew file mode 100644index 0000000000..fd9ecf5910--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0040_create_events_core.down.sql@@ -0,0 +1,5 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- table may predate this migration (created via dev-tables.sh on v4 preview+-- deployments) and may hold production-grade event data. Rolling back drops+-- that data regardless of which path created the table.+DROP TABLE IF EXISTS events_core ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/clustered/0040_create_events_core.up.sql b/packages/shared/clickhouse/migrations/clustered/0040_create_events_core.up.sqlnew file mode 100644index 0000000000..ab53c989e8--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0040_create_events_core.up.sql@@ -0,0 +1,123 @@+CREATE TABLE IF NOT EXISTS events_core ON CLUSTER default+(+ project_id String,+ trace_id String,+ span_id String,+ parent_span_id String,++ start_time DateTime64(6),+ end_time Nullable(DateTime64(6)),++ -- Core properties+ name String,+ type LowCardinality(String),+ environment LowCardinality(String) DEFAULT 'default',+ version String,+ release String,+ trace_name String,+ user_id String,+ session_id String,+ tags Array(String),+ level LowCardinality(String),+ status_message String,+ completion_start_time Nullable(DateTime64(6)),+ is_app_root Bool DEFAULT false,++ -- Updateable properties+ bookmarked Bool DEFAULT false,+ public Bool DEFAULT false,++ -- Prompt+ prompt_id String,+ prompt_name String,+ prompt_version Nullable(UInt16),++ -- Model+ model_id String,+ provided_model_name String,+ model_parameters String,++ -- Usage+ provided_usage_details Map(LowCardinality(String), UInt64),+ usage_details Map(LowCardinality(String), UInt64),+ provided_cost_details Map(LowCardinality(String), Decimal(18,12)),+ cost_details Map(LowCardinality(String), Decimal(18,12)),+ calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),+ calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ total_cost Decimal(18, 12) ALIAS cost_details['total'],++ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),++ -- Tools+ tool_definitions Map(String, String),+ tool_calls Array(String),+ tool_call_names Array(String),++ -- I/O+ input String,+ input_length UInt64 MATERIALIZED lengthUTF8(input),+ output String,+ output_length UInt64 MATERIALIZED lengthUTF8(output),++ -- Metadata+ metadata_names Array(String),+ metadata_values Array(String),++ -- Experiment properties+ experiment_id String,+ experiment_name String,+ experiment_metadata_names Array(String),+ experiment_metadata_values Array(String),+ experiment_description String,+ experiment_dataset_id String,+ experiment_item_id String,+ experiment_item_version Nullable(DateTime64(6)),+ experiment_item_expected_output String,+ experiment_item_metadata_names Array(String),+ experiment_item_metadata_values Array(String),+ experiment_item_root_span_id String,++ -- Source metadata (Instrumentation)+ source LowCardinality(String),+ service_name String,+ service_version String,+ scope_name String,+ scope_version String,+ telemetry_sdk_language LowCardinality(String),+ telemetry_sdk_name String,+ telemetry_sdk_version String,++ -- Generic props+ blob_storage_file_path String,+ event_bytes UInt64,+ created_at DateTime64(6) DEFAULT now(),+ updated_at DateTime64(6) DEFAULT now(),+ event_ts DateTime64(6),+ is_deleted UInt8,++ -- Indexes+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,+ INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,+ INDEX idx_provided_model_name provided_model_name TYPE bloom_filter(0.01) GRANULARITY 2,+ INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_metadata_names metadata_names TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha)+)+ENGINE = ReplicatedReplacingMergeTree(event_ts, is_deleted)+PARTITION BY toYYYYMM(start_time)+PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))+ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)+SAMPLE BY xxHash32(trace_id)+SETTINGS+ enable_block_number_column = 1,+ enable_block_offset_column = 1,+ prewarm_mark_cache = 1,+ prewarm_primary_key_cache = 1,+ enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/clustered/0041_create_events_core_mv.down.sql b/packages/shared/clickhouse/migrations/clustered/0041_create_events_core_mv.down.sqlnew file mode 100644index 0000000000..dacd2eb194--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0041_create_events_core_mv.down.sql@@ -0,0 +1,4 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- view may predate this migration (created via dev-tables.sh on v4 preview+-- deployments). Dropping it stops events_core from being populated.+DROP VIEW IF EXISTS events_core_mv ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/clustered/0041_create_events_core_mv.up.sql b/packages/shared/clickhouse/migrations/clustered/0041_create_events_core_mv.up.sqlnew file mode 100644index 0000000000..3c2db389da--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0041_create_events_core_mv.up.sql@@ -0,0 +1,69 @@+CREATE MATERIALIZED VIEW IF NOT EXISTS events_core_mv ON CLUSTER default TO events_core AS+SELECT+ project_id,+ trace_id,+ span_id,+ parent_span_id,+ start_time,+ end_time,+ name,+ type,+ environment,+ version,+ release,+ trace_name,+ user_id,+ session_id,+ tags,+ level,+ status_message,+ completion_start_time,+ is_app_root,+ bookmarked,+ public,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ usage_pricing_tier_id,+ usage_pricing_tier_name,+ tool_definitions,+ tool_calls,+ tool_call_names,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted+FROM events_full;diff --git a/packages/shared/clickhouse/migrations/clustered/0042_add_events_ingestion_attribution_columns.down.sql b/packages/shared/clickhouse/migrations/clustered/0042_add_events_ingestion_attribution_columns.down.sqlnew file mode 100644index 0000000000..1ba2f66a48--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0042_add_events_ingestion_attribution_columns.down.sql@@ -0,0 +1,82 @@+ALTER TABLE events_core_mv ON CLUSTER default MODIFY QUERY+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,+ is_app_root,+ bookmarked,+ public,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ usage_pricing_tier_id,+ usage_pricing_tier_name,+ tool_definitions,+ tool_calls,+ tool_call_names,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted+FROM events_full+SETTINGS enable_full_text_index = 1;++ALTER TABLE events_core ON CLUSTER default DROP COLUMN IF EXISTS ingestion_sdk_version SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_core ON CLUSTER default DROP COLUMN IF EXISTS ingestion_sdk_name SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_core ON CLUSTER default DROP COLUMN IF EXISTS ingestion_api_key SETTINGS enable_full_text_index = 1, alter_sync = 2;++ALTER TABLE events_full ON CLUSTER default DROP COLUMN IF EXISTS ingestion_sdk_version SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_full ON CLUSTER default DROP COLUMN IF EXISTS ingestion_sdk_name SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_full ON CLUSTER default DROP COLUMN IF EXISTS ingestion_api_key SETTINGS enable_full_text_index = 1, alter_sync = 2;++ALTER TABLE observations_batch_staging ON CLUSTER default DROP COLUMN IF EXISTS ingestion_sdk_version SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE observations_batch_staging ON CLUSTER default DROP COLUMN IF EXISTS ingestion_sdk_name SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE observations_batch_staging ON CLUSTER default DROP COLUMN IF EXISTS ingestion_api_key SETTINGS enable_full_text_index = 1, alter_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0042_add_events_ingestion_attribution_columns.up.sql b/packages/shared/clickhouse/migrations/clustered/0042_add_events_ingestion_attribution_columns.up.sqlnew file mode 100644index 0000000000..b751b5a26b--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0042_add_events_ingestion_attribution_columns.up.sql@@ -0,0 +1,103 @@+ALTER TABLE observations_batch_staging ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE observations_batch_staging ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE observations_batch_staging ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1, alter_sync = 2;++ALTER TABLE events_full ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_full ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_full ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1, alter_sync = 2;++ALTER TABLE events_core ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_core ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_core ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1, alter_sync = 2;++ALTER TABLE events_core_mv ON CLUSTER default MODIFY QUERY+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,+ is_app_root,+ bookmarked,+ public,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ usage_pricing_tier_id,+ usage_pricing_tier_name,+ tool_definitions,+ tool_calls,+ tool_call_names,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted,+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version+FROM events_full+SETTINGS enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/clustered/0043_add_events_metadata_ngram_index.down.sql b/packages/shared/clickhouse/migrations/clustered/0043_add_events_metadata_ngram_index.down.sqlnew file mode 100644index 0000000000..326efbcd77--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0043_add_events_metadata_ngram_index.down.sql@@ -0,0 +1,2 @@+ALTER TABLE events_full ON CLUSTER default DROP INDEX IF EXISTS idx_fts_metadata_values_ngram SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_core ON CLUSTER default DROP INDEX IF EXISTS idx_fts_metadata_values_ngram SETTINGS enable_full_text_index = 1, alter_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0043_add_events_metadata_ngram_index.up.sql b/packages/shared/clickhouse/migrations/clustered/0043_add_events_metadata_ngram_index.up.sqlnew file mode 100644index 0000000000..c3080c737d--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0043_add_events_metadata_ngram_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE events_full ON CLUSTER default ADD INDEX IF NOT EXISTS idx_fts_metadata_values_ngram arrayStringConcat(metadata_values) TYPE ngrambf_v1(4, 32000, 3, 0) GRANULARITY 2 SETTINGS enable_full_text_index = 1, alter_sync = 2;+ALTER TABLE events_core ON CLUSTER default ADD INDEX IF NOT EXISTS idx_fts_metadata_values_ngram arrayStringConcat(metadata_values) TYPE ngrambf_v1(4, 32000, 3, 0) GRANULARITY 2 SETTINGS enable_full_text_index = 1, alter_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0038_create_observations_batch_staging.down.sql b/packages/shared/clickhouse/migrations/unclustered/0038_create_observations_batch_staging.down.sqlnew file mode 100644index 0000000000..1f7193f389--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0038_create_observations_batch_staging.down.sql@@ -0,0 +1,5 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- table may predate this migration (created via dev-tables.sh on v4 preview+-- deployments) and may hold production-grade event data. Rolling back drops+-- that data regardless of which path created the table.+DROP TABLE IF EXISTS observations_batch_staging;diff --git a/packages/shared/clickhouse/migrations/unclustered/0038_create_observations_batch_staging.up.sql b/packages/shared/clickhouse/migrations/unclustered/0038_create_observations_batch_staging.up.sqlnew file mode 100644index 0000000000..757131dbdd--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0038_create_observations_batch_staging.up.sql@@ -0,0 +1,51 @@+CREATE TABLE IF NOT EXISTS observations_batch_staging+(+ id String,+ trace_id String,+ project_id String,+ type LowCardinality(String),+ parent_observation_id Nullable(String),+ start_time DateTime64(3),+ end_time Nullable(DateTime64(3)),+ name String,+ metadata Map(LowCardinality(String), String),+ level LowCardinality(String),+ status_message Nullable(String),+ version Nullable(String),+ input Nullable(String) CODEC(ZSTD(3)),+ output Nullable(String) CODEC(ZSTD(3)),+ provided_model_name Nullable(String),+ internal_model_id Nullable(String),+ model_parameters Nullable(String),+ provided_usage_details Map(LowCardinality(String), UInt64),+ usage_details Map(LowCardinality(String), UInt64),+ provided_cost_details Map(LowCardinality(String), Decimal64(12)),+ cost_details Map(LowCardinality(String), Decimal64(12)),+ total_cost Nullable(Decimal64(12)),+ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),+ tool_definitions Map(String, String),+ tool_calls Array(String),+ tool_call_names Array(String),+ completion_start_time Nullable(DateTime64(3)),+ prompt_id Nullable(String),+ prompt_name Nullable(String),+ prompt_version Nullable(UInt16),+ created_at DateTime64(3) DEFAULT now(),+ updated_at DateTime64(3) DEFAULT now(),+ event_ts DateTime64(3),+ is_deleted UInt8,+ s3_first_seen_timestamp DateTime64(3),+ environment LowCardinality(String) DEFAULT 'default'+)+ENGINE = ReplacingMergeTree(event_ts, is_deleted)+PARTITION BY toStartOfInterval(s3_first_seen_timestamp, INTERVAL 3 MINUTE)+PRIMARY KEY (project_id, toDate(s3_first_seen_timestamp))+ORDER BY (+ project_id,+ toDate(s3_first_seen_timestamp),+ trace_id,+ id+)+TTL toDateTime(s3_first_seen_timestamp) + INTERVAL 48 HOUR+SETTINGS ttl_only_drop_parts = 1;diff --git a/packages/shared/clickhouse/migrations/unclustered/0039_create_events_full.down.sql b/packages/shared/clickhouse/migrations/unclustered/0039_create_events_full.down.sqlnew file mode 100644index 0000000000..9280e87133--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0039_create_events_full.down.sql@@ -0,0 +1,5 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- table may predate this migration (created via dev-tables.sh on v4 preview+-- deployments) and may hold production-grade event data. Rolling back drops+-- that data regardless of which path created the table.+DROP TABLE IF EXISTS events_full;diff --git a/packages/shared/clickhouse/migrations/unclustered/0039_create_events_full.up.sql b/packages/shared/clickhouse/migrations/unclustered/0039_create_events_full.up.sqlnew file mode 100644index 0000000000..c14b38ef47--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0039_create_events_full.up.sql@@ -0,0 +1,124 @@+CREATE TABLE IF NOT EXISTS events_full+(+ project_id String,+ trace_id String,+ span_id String,+ parent_span_id String,++ start_time DateTime64(6),+ end_time Nullable(DateTime64(6)),++ -- Core properties+ name String,+ type LowCardinality(String),+ environment LowCardinality(String) DEFAULT 'default',+ version String,+ release String,+ trace_name String,+ user_id String,+ session_id String,+ tags Array(String),+ level LowCardinality(String),+ status_message String,+ completion_start_time Nullable(DateTime64(6)),+ is_app_root Bool DEFAULT false,++ -- Updateable properties+ bookmarked Bool DEFAULT false,+ public Bool DEFAULT false,++ -- Prompt+ prompt_id String,+ prompt_name String,+ prompt_version Nullable(UInt16),++ -- Model+ model_id String,+ provided_model_name String,+ model_parameters String,++ -- Usage and Cost+ provided_usage_details Map(LowCardinality(String), UInt64),+ usage_details Map(LowCardinality(String), UInt64),+ provided_cost_details Map(LowCardinality(String), Decimal(18,12)),+ cost_details Map(LowCardinality(String), Decimal(18,12)),+ calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),+ calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ total_cost Decimal(18, 12) ALIAS cost_details['total'],++ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),++ -- Tools+ tool_definitions Map(String, String),+ tool_calls Array(String),+ tool_call_names Array(String),++ -- I/O+ input String CODEC(ZSTD(3)),+ input_length UInt64 MATERIALIZED lengthUTF8(input),+ output String CODEC(ZSTD(3)),+ output_length UInt64 MATERIALIZED lengthUTF8(output),++ -- Metadata+ metadata_names Array(String),+ metadata_values Array(String),++ -- Experiment properties+ experiment_id String,+ experiment_name String,+ experiment_metadata_names Array(String),+ experiment_metadata_values Array(String),+ experiment_description String,+ experiment_dataset_id String,+ experiment_item_id String,+ experiment_item_version Nullable(DateTime64(6)),+ experiment_item_expected_output String,+ experiment_item_metadata_names Array(String),+ experiment_item_metadata_values Array(String),+ experiment_item_root_span_id String,++ -- Source metadata (Instrumentation)+ source LowCardinality(String),+ service_name String,+ service_version String,+ scope_name String,+ scope_version String,+ telemetry_sdk_language LowCardinality(String),+ telemetry_sdk_name String,+ telemetry_sdk_version String,++ -- Generic props+ blob_storage_file_path String,+ event_bytes UInt64,+ created_at DateTime64(6) DEFAULT now(),+ updated_at DateTime64(6) DEFAULT now(),+ event_ts DateTime64(6),+ is_deleted UInt8,++ -- Indexes+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,+ INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,+ INDEX idx_fts_input_low lower(input) TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_output_low lower(output) TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha)+)+ENGINE = ReplacingMergeTree(event_ts, is_deleted)+PARTITION BY toYYYYMM(start_time)+PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))+ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)+SAMPLE BY xxHash32(trace_id)+SETTINGS+ index_granularity_bytes = '64Mi', -- Default 10MiB. Prevents very small granules due to large rows.+ merge_max_block_size_bytes = '64Mi',+ enable_block_number_column = 1,+ enable_block_offset_column = 1,+ prewarm_mark_cache = 1,+ prewarm_primary_key_cache = 1,+ enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/unclustered/0040_create_events_core.down.sql b/packages/shared/clickhouse/migrations/unclustered/0040_create_events_core.down.sqlnew file mode 100644index 0000000000..c263c98542--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0040_create_events_core.down.sql@@ -0,0 +1,5 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- table may predate this migration (created via dev-tables.sh on v4 preview+-- deployments) and may hold production-grade event data. Rolling back drops+-- that data regardless of which path created the table.+DROP TABLE IF EXISTS events_core;diff --git a/packages/shared/clickhouse/migrations/unclustered/0040_create_events_core.up.sql b/packages/shared/clickhouse/migrations/unclustered/0040_create_events_core.up.sqlnew file mode 100644index 0000000000..fb5df27191--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0040_create_events_core.up.sql@@ -0,0 +1,123 @@+CREATE TABLE IF NOT EXISTS events_core+(+ project_id String,+ trace_id String,+ span_id String,+ parent_span_id String,++ start_time DateTime64(6),+ end_time Nullable(DateTime64(6)),++ -- Core properties+ name String,+ type LowCardinality(String),+ environment LowCardinality(String) DEFAULT 'default',+ version String,+ release String,+ trace_name String,+ user_id String,+ session_id String,+ tags Array(String),+ level LowCardinality(String),+ status_message String,+ completion_start_time Nullable(DateTime64(6)),+ is_app_root Bool DEFAULT false,++ -- Updateable properties+ bookmarked Bool DEFAULT false,+ public Bool DEFAULT false,++ -- Prompt+ prompt_id String,+ prompt_name String,+ prompt_version Nullable(UInt16),++ -- Model+ model_id String,+ provided_model_name String,+ model_parameters String,++ -- Usage+ provided_usage_details Map(LowCardinality(String), UInt64),+ usage_details Map(LowCardinality(String), UInt64),+ provided_cost_details Map(LowCardinality(String), Decimal(18,12)),+ cost_details Map(LowCardinality(String), Decimal(18,12)),+ calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),+ calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),+ total_cost Decimal(18, 12) ALIAS cost_details['total'],++ usage_pricing_tier_id Nullable(String),+ usage_pricing_tier_name Nullable(String),++ -- Tools+ tool_definitions Map(String, String),+ tool_calls Array(String),+ tool_call_names Array(String),++ -- I/O+ input String,+ input_length UInt64 MATERIALIZED lengthUTF8(input),+ output String,+ output_length UInt64 MATERIALIZED lengthUTF8(output),++ -- Metadata+ metadata_names Array(String),+ metadata_values Array(String),++ -- Experiment properties+ experiment_id String,+ experiment_name String,+ experiment_metadata_names Array(String),+ experiment_metadata_values Array(String),+ experiment_description String,+ experiment_dataset_id String,+ experiment_item_id String,+ experiment_item_version Nullable(DateTime64(6)),+ experiment_item_expected_output String,+ experiment_item_metadata_names Array(String),+ experiment_item_metadata_values Array(String),+ experiment_item_root_span_id String,++ -- Source metadata (Instrumentation)+ source LowCardinality(String),+ service_name String,+ service_version String,+ scope_name String,+ scope_version String,+ telemetry_sdk_language LowCardinality(String),+ telemetry_sdk_name String,+ telemetry_sdk_version String,++ -- Generic props+ blob_storage_file_path String,+ event_bytes UInt64,+ created_at DateTime64(6) DEFAULT now(),+ updated_at DateTime64(6) DEFAULT now(),+ event_ts DateTime64(6),+ is_deleted UInt8,++ -- Indexes+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,+ INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,+ INDEX idx_provided_model_name provided_model_name TYPE bloom_filter(0.01) GRANULARITY 2,+ INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_metadata_names metadata_names TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),+ INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha)+)+ENGINE = ReplacingMergeTree(event_ts, is_deleted)+PARTITION BY toYYYYMM(start_time)+PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))+ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)+SAMPLE BY xxHash32(trace_id)+SETTINGS+ enable_block_number_column = 1,+ enable_block_offset_column = 1,+ prewarm_mark_cache = 1,+ prewarm_primary_key_cache = 1,+ enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/unclustered/0041_create_events_core_mv.down.sql b/packages/shared/clickhouse/migrations/unclustered/0041_create_events_core_mv.down.sqlnew file mode 100644index 0000000000..1e4578cc48--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0041_create_events_core_mv.down.sql@@ -0,0 +1,4 @@+-- WARNING: destructive rollback. The up migration uses IF NOT EXISTS, so this+-- view may predate this migration (created via dev-tables.sh on v4 preview+-- deployments). Dropping it stops events_core from being populated.+DROP VIEW IF EXISTS events_core_mv;diff --git a/packages/shared/clickhouse/migrations/unclustered/0041_create_events_core_mv.up.sql b/packages/shared/clickhouse/migrations/unclustered/0041_create_events_core_mv.up.sqlnew file mode 100644index 0000000000..40f95a62f2--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0041_create_events_core_mv.up.sql@@ -0,0 +1,69 @@+CREATE MATERIALIZED VIEW IF NOT EXISTS events_core_mv TO events_core AS+SELECT+ project_id,+ trace_id,+ span_id,+ parent_span_id,+ start_time,+ end_time,+ name,+ type,+ environment,+ version,+ release,+ trace_name,+ user_id,+ session_id,+ tags,+ level,+ status_message,+ completion_start_time,+ is_app_root,+ bookmarked,+ public,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ usage_pricing_tier_id,+ usage_pricing_tier_name,+ tool_definitions,+ tool_calls,+ tool_call_names,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted+FROM events_full;diff --git a/packages/shared/clickhouse/migrations/unclustered/0042_add_events_ingestion_attribution_columns.down.sql b/packages/shared/clickhouse/migrations/unclustered/0042_add_events_ingestion_attribution_columns.down.sqlnew file mode 100644index 0000000000..87863a03ac--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0042_add_events_ingestion_attribution_columns.down.sql@@ -0,0 +1,82 @@+ALTER TABLE events_core_mv MODIFY QUERY+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,+ is_app_root,+ bookmarked,+ public,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ usage_pricing_tier_id,+ usage_pricing_tier_name,+ tool_definitions,+ tool_calls,+ tool_call_names,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted+FROM events_full+SETTINGS enable_full_text_index = 1;++ALTER TABLE events_core DROP COLUMN IF EXISTS ingestion_sdk_version SETTINGS enable_full_text_index = 1;+ALTER TABLE events_core DROP COLUMN IF EXISTS ingestion_sdk_name SETTINGS enable_full_text_index = 1;+ALTER TABLE events_core DROP COLUMN IF EXISTS ingestion_api_key SETTINGS enable_full_text_index = 1;++ALTER TABLE events_full DROP COLUMN IF EXISTS ingestion_sdk_version SETTINGS enable_full_text_index = 1;+ALTER TABLE events_full DROP COLUMN IF EXISTS ingestion_sdk_name SETTINGS enable_full_text_index = 1;+ALTER TABLE events_full DROP COLUMN IF EXISTS ingestion_api_key SETTINGS enable_full_text_index = 1;++ALTER TABLE observations_batch_staging DROP COLUMN IF EXISTS ingestion_sdk_version SETTINGS enable_full_text_index = 1;+ALTER TABLE observations_batch_staging DROP COLUMN IF EXISTS ingestion_sdk_name SETTINGS enable_full_text_index = 1;+ALTER TABLE observations_batch_staging DROP COLUMN IF EXISTS ingestion_api_key SETTINGS enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/unclustered/0042_add_events_ingestion_attribution_columns.up.sql b/packages/shared/clickhouse/migrations/unclustered/0042_add_events_ingestion_attribution_columns.up.sqlnew file mode 100644index 0000000000..7a43d0fb2a--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0042_add_events_ingestion_attribution_columns.up.sql@@ -0,0 +1,103 @@+ALTER TABLE observations_batch_staging+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1;+ALTER TABLE observations_batch_staging+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;+ALTER TABLE observations_batch_staging+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_full+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1;+ALTER TABLE events_full+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;+ALTER TABLE events_full+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_core+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1;+ALTER TABLE events_core+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;+ALTER TABLE events_core+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_core_mv MODIFY QUERY+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,+ is_app_root,+ bookmarked,+ public,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ usage_pricing_tier_id,+ usage_pricing_tier_name,+ tool_definitions,+ tool_calls,+ tool_call_names,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted,+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version+FROM events_full+SETTINGS enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/unclustered/0043_add_events_metadata_ngram_index.down.sql b/packages/shared/clickhouse/migrations/unclustered/0043_add_events_metadata_ngram_index.down.sqlnew file mode 100644index 0000000000..09d2b99e91--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0043_add_events_metadata_ngram_index.down.sql@@ -0,0 +1,2 @@+ALTER TABLE events_full DROP INDEX IF EXISTS idx_fts_metadata_values_ngram SETTINGS enable_full_text_index = 1;+ALTER TABLE events_core DROP INDEX IF EXISTS idx_fts_metadata_values_ngram SETTINGS enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/migrations/unclustered/0043_add_events_metadata_ngram_index.up.sql b/packages/shared/clickhouse/migrations/unclustered/0043_add_events_metadata_ngram_index.up.sqlnew file mode 100644index 0000000000..2c864662a0--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0043_add_events_metadata_ngram_index.up.sql@@ -0,0 +1,2 @@+ALTER TABLE events_full ADD INDEX IF NOT EXISTS idx_fts_metadata_values_ngram arrayStringConcat(metadata_values) TYPE ngrambf_v1(4, 32000, 3, 0) GRANULARITY 2 SETTINGS enable_full_text_index = 1;+ALTER TABLE events_core ADD INDEX IF NOT EXISTS idx_fts_metadata_values_ngram arrayStringConcat(metadata_values) TYPE ngrambf_v1(4, 32000, 3, 0) GRANULARITY 2 SETTINGS enable_full_text_index = 1;diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex f0911667b2..1161b2a578 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -2,7 +2,8 @@# Development-only ClickHouse table creation script# This script is for creating experimental/development tables that are not yet-# ready to be part of the official migration system.+# ready to be part of the official migration system, and for seeding the v4+# events tables with local sample data.## Usage:# pnpm run ch:dev-tables (from packages/shared/)@@ -12,22 +13,9 @@# - pnpm run dx-f# - pnpm run ch:reset#-# Self-hosted v4 rollout note:-# The events_full / events_core / events_core_mv / observations_batch_staging-# definitions below are intentionally NOT promoted to production CH migrations-# yet. They depend on ClickHouse features that are only available on recent-# versions:-# * `enable_block_number_column` / `enable_block_offset_column` table SETTINGS require ClickHouse >= 24.5.-# * `text` indexes and `enable_full_text_index` require ClickHouse >= 25.x.-# Self-hosters on older versions would be blocked from adopting v4 if we-# shipped these inline as migrations. Once v4 becomes the mainline and we can-# assume a 25.12+ minimum, these definitions will be promoted to proper-# migrations. Until then, this script is the documented way to roll out the-# v4 events pipeline tables.--# When making changes below, treat them like migrations, i.e. DO NOT modify the column inline.-# Instead add a table mutation adding a net new column.-# Also, populate the migrations in https://docs.google.com/document/d/1bvz3FUFn3T4rfJ_U1qIh36FcJGfUVQwdAIOAHa3wPnA.+# When making changes below, treat them like migrations, i.e. DO NOT modify the+# column inline. Instead add a table mutation adding a net new column. Core+# events-table schema changes belong in a new ClickHouse migration, not here.# Load environment variables[ -f ../../.env ] && source ../../.env@@ -89,401 +77,6 @@ clickhouse client \--database="${CLICKHOUSE_DB}" \--multiquery <<'EOF'--- Staging table for the dual-write pipeline that populates events_full.--- Ingestion writes every observation (and trace-as-synthetic-observation) here--- with an s3_first_seen_timestamp; the periodic event-propagation job in the--- worker reads completed 3-minute partitions, joins them with `traces`, and--- inserts the result into `events_full`.------ Partitions are automatically expired after 48 hours via TTL. The 48h window--- (vs. the 12h used internally for Langfuse Cloud) gives self-hosters a--- multi-day grace period to recover the propagation job after an incident--- without losing staging data. `ttl_only_drop_parts = 1` ensures only complete--- partitions are dropped, never individual rows.-CREATE TABLE IF NOT EXISTS observations_batch_staging-(- id String,- trace_id String,- project_id String,- type LowCardinality(String),- parent_observation_id Nullable(String),- start_time DateTime64(3),- end_time Nullable(DateTime64(3)),- name String,- metadata Map(LowCardinality(String), String),- level LowCardinality(String),- status_message Nullable(String),- version Nullable(String),- input Nullable(String) CODEC(ZSTD(3)),- output Nullable(String) CODEC(ZSTD(3)),- provided_model_name Nullable(String),- internal_model_id Nullable(String),- model_parameters Nullable(String),- provided_usage_details Map(LowCardinality(String), UInt64),- usage_details Map(LowCardinality(String), UInt64),- provided_cost_details Map(LowCardinality(String), Decimal64(12)),- cost_details Map(LowCardinality(String), Decimal64(12)),- total_cost Nullable(Decimal64(12)),- usage_pricing_tier_id Nullable(String),- usage_pricing_tier_name Nullable(String),- tool_definitions Map(String, String),- tool_calls Array(String),- tool_call_names Array(String),- completion_start_time Nullable(DateTime64(3)),- prompt_id Nullable(String),- prompt_name Nullable(String),- prompt_version Nullable(UInt16),- created_at DateTime64(3) DEFAULT now(),- updated_at DateTime64(3) DEFAULT now(),- event_ts DateTime64(3),- is_deleted UInt8,- s3_first_seen_timestamp DateTime64(3),- environment LowCardinality(String) DEFAULT 'default'-)-ENGINE = ReplacingMergeTree(event_ts, is_deleted)-PARTITION BY toStartOfInterval(s3_first_seen_timestamp, INTERVAL 3 MINUTE)-PRIMARY KEY (project_id, toDate(s3_first_seen_timestamp))-ORDER BY (- project_id,- toDate(s3_first_seen_timestamp),- trace_id,- id-)-TTL s3_first_seen_timestamp + INTERVAL 48 HOUR-SETTINGS ttl_only_drop_parts = 1;---- events_full is the immutable, full-fidelity event table that will eventually--- replace observations. It is populated by the worker propagation job that--- joins observations_batch_staging with traces and dataset_run_items.-CREATE TABLE IF NOT EXISTS events_full-(- project_id String,- trace_id String,- span_id String,- parent_span_id String,-- start_time DateTime64(6),- end_time Nullable(DateTime64(6)),-- -- Core properties- name String,- type LowCardinality(String),- environment LowCardinality(String) DEFAULT 'default',- version String,- release String,- trace_name String,- user_id String,- session_id String,- tags Array(String),- level LowCardinality(String),- status_message String,- completion_start_time Nullable(DateTime64(6)),- is_app_root Bool DEFAULT false,-- -- Updateable properties- bookmarked Bool DEFAULT false,- public Bool DEFAULT false,-- -- Prompt- prompt_id String,- prompt_name String,- prompt_version Nullable(UInt16),-- -- Model- model_id String,- provided_model_name String,- model_parameters String,-- -- Usage and Cost- provided_usage_details Map(LowCardinality(String), UInt64),- usage_details Map(LowCardinality(String), UInt64),- provided_cost_details Map(LowCardinality(String), Decimal(18,12)),- cost_details Map(LowCardinality(String), Decimal(18,12)),- calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),- calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),- calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),- total_cost Decimal(18, 12) ALIAS cost_details['total'],-- usage_pricing_tier_id Nullable(String),- usage_pricing_tier_name Nullable(String),-- -- Tools- tool_definitions Map(String, String),- tool_calls Array(String),- tool_call_names Array(String),-- -- I/O- input String CODEC(ZSTD(3)),- input_length UInt64 MATERIALIZED lengthUTF8(input),- output String CODEC(ZSTD(3)),- output_length UInt64 MATERIALIZED lengthUTF8(output),-- -- Metadata- metadata_names Array(String),- metadata_values Array(String),-- -- Experiment properties- experiment_id String,- experiment_name String,- experiment_metadata_names Array(String),- experiment_metadata_values Array(String),- experiment_description String,- experiment_dataset_id String,- experiment_item_id String,- experiment_item_version Nullable(DateTime64(6)),- experiment_item_expected_output String,- experiment_item_metadata_names Array(String),- experiment_item_metadata_values Array(String),- experiment_item_root_span_id String,-- -- Source metadata (Instrumentation)- source LowCardinality(String),- service_name String,- service_version String,- scope_name String,- scope_version String,- telemetry_sdk_language LowCardinality(String),- telemetry_sdk_name String,- telemetry_sdk_version String,-- -- Generic props- blob_storage_file_path String,- event_bytes UInt64,- created_at DateTime64(6) DEFAULT now(),- updated_at DateTime64(6) DEFAULT now(),- event_ts DateTime64(6),- is_deleted UInt8,-- -- Indexes- INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,- INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,- INDEX idx_fts_input_low lower(input) TYPE text(tokenizer = splitByNonAlpha),- INDEX idx_fts_output_low lower(output) TYPE text(tokenizer = splitByNonAlpha),- INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),- INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha)-)-ENGINE = ReplacingMergeTree(event_ts, is_deleted)-PARTITION BY toYYYYMM(start_time)-PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))-ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)-SAMPLE BY xxHash32(trace_id)-SETTINGS- index_granularity_bytes = '64Mi', -- Default 10MiB. Prevents very small granules due to large rows.- merge_max_block_size_bytes = '64Mi',- enable_block_number_column = 1,- enable_block_offset_column = 1,- prewarm_mark_cache = 1,- prewarm_primary_key_cache = 1,- enable_full_text_index = 1;---- events_core is the lightweight, query-optimized projection of events_full--- with truncated input/output/metadata. It is populated via the events_core_mv--- materialized view defined below.-CREATE TABLE IF NOT EXISTS events_core-(- project_id String,- trace_id String,- span_id String,- parent_span_id String,-- start_time DateTime64(6),- end_time Nullable(DateTime64(6)),-- -- Core properties- name String,- type LowCardinality(String),- environment LowCardinality(String) DEFAULT 'default',- version String,- release String,- trace_name String,- user_id String,- session_id String,- tags Array(String),- level LowCardinality(String),- status_message String,- completion_start_time Nullable(DateTime64(6)),- is_app_root Bool DEFAULT false,-- -- Updateable properties- bookmarked Bool DEFAULT false,- public Bool DEFAULT false,-- -- Prompt- prompt_id String,- prompt_name String,- prompt_version Nullable(UInt16),-- -- Model- model_id String,- provided_model_name String,- model_parameters String,-- -- Usage- provided_usage_details Map(LowCardinality(String), UInt64),- usage_details Map(LowCardinality(String), UInt64),- provided_cost_details Map(LowCardinality(String), Decimal(18,12)),- cost_details Map(LowCardinality(String), Decimal(18,12)),- calculated_input_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, cost_details))),- calculated_output_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, cost_details))),- calculated_total_cost Decimal(18, 12) MATERIALIZED arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0 OR positionCaseInsensitive(x.1, 'output') > 0, cost_details))),- total_cost Decimal(18, 12) ALIAS cost_details['total'],-- usage_pricing_tier_id Nullable(String),- usage_pricing_tier_name Nullable(String),-- -- Tools- tool_definitions Map(String, String),- tool_calls Array(String),- tool_call_names Array(String),-- -- I/O- input String,- input_length UInt64 MATERIALIZED lengthUTF8(input),- output String,- output_length UInt64 MATERIALIZED lengthUTF8(output),-- -- Metadata- metadata_names Array(String),- metadata_values Array(String),-- -- Experiment properties- experiment_id String,- experiment_name String,- experiment_metadata_names Array(String),- experiment_metadata_values Array(String),- experiment_description String,- experiment_dataset_id String,- experiment_item_id String,- experiment_item_version Nullable(DateTime64(6)),- experiment_item_expected_output String,- experiment_item_metadata_names Array(String),- experiment_item_metadata_values Array(String),- experiment_item_root_span_id String,-- -- Source metadata (Instrumentation)- source LowCardinality(String),- service_name String,- service_version String,- scope_name String,- scope_version String,- telemetry_sdk_language LowCardinality(String),- telemetry_sdk_name String,- telemetry_sdk_version String,-- -- Generic props- blob_storage_file_path String,- event_bytes UInt64,- created_at DateTime64(6) DEFAULT now(),- updated_at DateTime64(6) DEFAULT now(),- event_ts DateTime64(6),- is_deleted UInt8,-- -- Indexes- INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_user_id user_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,- INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,- INDEX idx_provided_model_name provided_model_name TYPE bloom_filter(0.01) GRANULARITY 2,- INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_metadata_names metadata_names TYPE bloom_filter(0.01) GRANULARITY 1,- INDEX idx_fts_metadata_values metadata_values TYPE text(tokenizer = splitByNonAlpha),- INDEX idx_fts_metadata_names metadata_names TYPE text(tokenizer = splitByNonAlpha)-)-ENGINE = ReplacingMergeTree(event_ts, is_deleted)-PARTITION BY toYYYYMM(start_time)-PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))-ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)-SAMPLE BY xxHash32(trace_id)-SETTINGS- enable_block_number_column = 1,- enable_block_offset_column = 1,- prewarm_mark_cache = 1,- prewarm_primary_key_cache = 1,- enable_full_text_index = 1;- -- cache_populated_by_fetch = 1; -- Not available in OSS ClickHouse---- Materialized view to populate events_core from events_full.-CREATE MATERIALIZED VIEW IF NOT EXISTS events_core_mv TO events_core AS-SELECT- project_id,- trace_id,- span_id,- parent_span_id,- start_time,- end_time,- name,- type,- environment,- version,- release,- trace_name,- user_id,- session_id,- tags,- level,- status_message,- completion_start_time,- is_app_root,- bookmarked,- public,- prompt_id,- prompt_name,- prompt_version,- model_id,- provided_model_name,- model_parameters,- provided_usage_details,- usage_details,- provided_cost_details,- cost_details,- usage_pricing_tier_id,- usage_pricing_tier_name,- tool_definitions,- tool_calls,- tool_call_names,- leftUTF8(input, 200) as input,- leftUTF8(output, 200) as output,- metadata_names,- arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,- experiment_id,- experiment_name,- experiment_metadata_names,- experiment_metadata_values,- experiment_description,- experiment_dataset_id,- experiment_item_id,- experiment_item_version,- experiment_item_expected_output,- experiment_item_metadata_names,- experiment_item_metadata_values,- experiment_item_root_span_id,- source,- service_name,- service_version,- scope_name,- scope_version,- telemetry_sdk_language,- telemetry_sdk_name,- telemetry_sdk_version,- blob_storage_file_path,- event_bytes,- created_at,- updated_at,- event_ts,- is_deleted-FROM events_full;---- Event metadata substring acceleration. Keep this as a post-create mutation--- while events tables are managed through this dev-table workflow.-ALTER TABLE events_full ADD INDEX IF NOT EXISTS idx_fts_metadata_values_ngram arrayStringConcat(metadata_values) TYPE ngrambf_v1(4, 32000, 3, 0) GRANULARITY 2 SETTINGS enable_full_text_index = 1;-ALTER TABLE events_core ADD INDEX IF NOT EXISTS idx_fts_metadata_values_ngram arrayStringConcat(metadata_values) TYPE ngrambf_v1(4, 32000, 3, 0) GRANULARITY 2 SETTINGS enable_full_text_index = 1;--- Diagnostic table to track event size distributions across projects.-- Every insert (including updates) produces a row — no deduplication.-- See LFE-9402 for context.@@ -530,165 +123,13 @@ SELECTbyteSize(*) AS total_sizeFROM traces;-CREATE VIEW analytics_events_core AS-SELECT- project_id,- toStartOfHour(start_time) AS hour,- sumMap(map(type, toUInt64(1))) AS count_types,- uniq(trace_id) AS count_traces,- uniq(span_id) AS count_spans,- uniqIf(trace_name, trace_name != '') AS count_trace_names,- max(user_id != '') AS has_users,- uniqIf(user_id, user_id != '') AS count_users,- max(session_id != '') AS has_sessions,- uniqIf(session_id, session_id != '') AS count_sessions,- max(if(environment != 'default', 1, 0)) AS has_environments,- uniq(environment) as count_environments,- max(length(tags) > 0) AS has_tags,- uniqArray(tags) AS count_unique_tags,- max(level != 'DEFAULT') AS has_level,- max(provided_model_name != '') AS has_provided_model_name,- uniqIf(provided_model_name, provided_model_name != '') AS count_models,- max(length(provided_usage_details) > 0) AS has_provided_usage_details,- max(length(provided_cost_details) > 0) AS has_provided_cost_details,- max(prompt_name != '') AS has_prompt_name,- max(length(tool_definitions) > 0) AS has_tool_definitions,- max(length(tool_calls) > 0) AS has_tool_calls,- uniqArray(metadata_names) AS count_unique_metadata_names,- max(experiment_name != '') AS has_experiment_names,- uniqIf(experiment_name, experiment_name != '') AS count_unique_experiment_names,- sum(event_bytes) AS sum_event_bytes,- sumMap(map(if(source = '', '-', source), toUInt64(1))) AS count_sources,- uniqIf(service_name, service_name != '') as count_service_names,- sumMap(map(if(scope_name = '', '-', concat(scope_name, '-', scope_version)), toUInt64(1))) AS count_scopes,- sumMap(map(if(telemetry_sdk_language = '', '-', telemetry_sdk_language), toUInt64(1))) AS count_telemetry_sdk_languages,- sumMap(map(if(telemetry_sdk_name = '', '-', concat(telemetry_sdk_language, '-', telemetry_sdk_name, '-', telemetry_sdk_version)), toUInt64(1))) AS count_sdk_telemetry_sdks-FROM events_core-WHERE toStartOfHour(start_time) <= toStartOfHour(subtractHours(now(), 1))-GROUP BY project_id, hour;---- Apply dev-table migrations for ingestion attribution.-ALTER TABLE observations_batch_staging- ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''- SETTINGS enable_full_text_index = 1;--ALTER TABLE observations_batch_staging- ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'- SETTINGS enable_full_text_index = 1;--ALTER TABLE observations_batch_staging- ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'- SETTINGS enable_full_text_index = 1;--ALTER TABLE events_full- ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''- SETTINGS enable_full_text_index = 1;--ALTER TABLE events_full- ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'- SETTINGS enable_full_text_index = 1;--ALTER TABLE events_full- ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'- SETTINGS enable_full_text_index = 1;--ALTER TABLE events_core- ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''- SETTINGS enable_full_text_index = 1;--ALTER TABLE events_core- ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'- SETTINGS enable_full_text_index = 1;--ALTER TABLE events_core- ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'- SETTINGS enable_full_text_index = 1;---- Update events MV-ALTER TABLE events_core_mv MODIFY QUERY-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,- is_app_root,- bookmarked,- public,- prompt_id,- prompt_name,- prompt_version,- model_id,- provided_model_name,- model_parameters,- provided_usage_details,- usage_details,- provided_cost_details,- cost_details,- usage_pricing_tier_id,- usage_pricing_tier_name,- tool_definitions,- tool_calls,- tool_call_names,- leftUTF8(input, 200) as input,- leftUTF8(output, 200) as output,- metadata_names,- arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,- experiment_id,- experiment_name,- experiment_metadata_names,- experiment_metadata_values,- experiment_description,- experiment_dataset_id,- experiment_item_id,- experiment_item_version,- experiment_item_expected_output,- experiment_item_metadata_names,- experiment_item_metadata_values,- experiment_item_root_span_id,- source,- service_name,- service_version,- scope_name,- scope_version,- telemetry_sdk_language,- telemetry_sdk_name,- telemetry_sdk_version,- blob_storage_file_path,- event_bytes,- created_at,- updated_at,- event_ts,- is_deleted,- ingestion_api_key,- ingestion_sdk_name,- ingestion_sdk_version-FROM events_full-SETTINGS enable_full_text_index = 1;---- Append-only re-definition of analytics_events_core adding ingested_sdks.--- Must stay after the ingestion attribution ALTERs above: the view reads--- ingestion_sdk_name/ingestion_sdk_version from events_core.----- PROD ROLLOUT: unlike analytics_scores (managed via numbered migrations),--- this view is NOT migration-managed because events_core only exists in--- cloud environments (see header note). Any change here must be applied--- manually as DROP VIEW IF EXISTS followed by CREATE VIEW in every cloud--- region (eu, us, hipaa, jp) and recorded in the migrations doc linked in the--- header — otherwise the DWH S3 export silently misses the new columns.+-- this view is NOT migration-managed because it is a Cloud-only diagnostic+-- over events_core. Any change here must be applied manually as DROP VIEW IF+-- EXISTS followed by CREATE VIEW in every cloud region (eu, us, hipaa, jp)+-- and recorded in the migrations doc+-- (https://docs.google.com/document/d/1bvz3FUFn3T4rfJ_U1qIh36FcJGfUVQwdAIOAHa3wPnA)+-- — otherwise the DWH S3 export silently misses the new columns.DROP VIEW IF EXISTS analytics_events_core;CREATE VIEW analytics_events_core ASSELECTdiff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 8ae0bd89cc..ae3f8efb8c 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -309,9 +309,11 @@ const EnvSchema = z.object({// public API routes that rely on the legacy traces/observations tables.// The worker owns the writes; the web only needs to know whether legacy// tables are still being populated to decide whether to serve reads.+ // Defaults to `events_only` for the v4 target state (v3 shipped `legacy`);+ // keep this value in sync with worker/src/env.ts and web/src/env.mjs.LANGFUSE_MIGRATION_V4_WRITE_MODE: z.enum(["legacy", "dual", "events_only"])- .default("legacy"),+ .default("events_only"),LANGFUSE_S3_LIST_MAX_KEYS: z.coerce.number().positive().default(200),// Checksum algorithm for S3 DeleteObjects requests; unset keeps the SDKdiff --git a/web/src/env.mjs b/web/src/env.mjsindex 957356e120..b2cd821306 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -450,10 +450,11 @@ export const env = createEnv({LANGFUSE_API_TRACES_DEFAULT_FIELDS: z.string().optional(),LANGFUSE_API_TRACEBYID_DEFAULT_FIELDS: z.string().optional(),- // V4 preview opt-in. See LFE-9778.+ // V4 preview opt-in. See LFE-9778. Defaults on for the v4 target state so+ // the events read paths are available out of the box (v3 shipped "false").LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN: z.enum(["true", "false"])- .default("false"),+ .default("true"),// Legacy tracing search controlsLANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH: z@@ -463,9 +464,11 @@ export const env = createEnv({// public API routes that rely on the legacy traces/observations tables.// The worker owns the writes; the web only needs to know whether legacy// tables are still being populated to decide whether to serve reads.+ // Defaults to `events_only` for the v4 target state (v3 shipped `legacy`);+ // keep this value in sync with worker/src/env.ts and packages/shared/src/env.ts.LANGFUSE_MIGRATION_V4_WRITE_MODE: z.enum(["legacy", "dual", "events_only"])- .default("legacy"),+ .default("events_only"),// Temporary kill-switch for the observations v2 subquery-IN rewrite.LANGFUSE_OBSERVATIONS_V2_SUBQUERY_REWRITE: zdiff --git a/worker/src/__tests__/eventPropagationHealth.test.ts b/worker/src/__tests__/eventPropagationHealth.test.tsindex eff4a9f1e5..ef66698052 100644--- a/worker/src/__tests__/eventPropagationHealth.test.ts+++ b/worker/src/__tests__/eventPropagationHealth.test.ts@@ -1,6 +1,38 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";++import {+ evaluateEventPropagationStuck,+ getEventPropagationHealth,+} from "../features/health";++// Pin the write mode to events_only: the propagation worker registers for any+// mode that writes to events_full (dual AND events_only), so the health gate+// must stay active for both. See worker/src/app.ts.+vi.mock("../env", async (importOriginal) => {+ const mod = await importOriginal<typeof import("../env")>();+ return {+ ...mod,+ env: {+ ...mod.env,+ QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED: "true",+ LANGFUSE_MIGRATION_V4_WRITE_MODE: "events_only",+ },+ };+});++vi.mock("../features/eventPropagation/handleEventPropagationJob", () => ({+ getLastRunStartedAt: vi.fn().mockResolvedValue(null),+ getLastProcessedPartition: vi.fn().mockResolvedValue(null),+}));++describe("getEventPropagationHealth", () => {+ it("keeps the liveness gate enabled in events_only write mode", async () => {+ const health = await getEventPropagationHealth();-import { evaluateEventPropagationStuck } from "../features/health";+ expect(health.enabled).toBe(true);+ expect(health.stuck).toBe(false); // no heartbeat yet -> not stuck+ });+});describe("evaluateEventPropagationStuck", () => {const nowMs = 1_700_000_000_000;diff --git a/worker/src/env.ts b/worker/src/env.tsindex 08c4301665..1fc9930102 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -496,24 +496,30 @@ const EnvSchema = z.object({.default(5),// V4 migration flags. See LFE-9778.+ // Defaults reflect the Langfuse v4 target state: net-new deployments write+ // straight into the events tables. The v3 line ships these as `legacy` /+ // `dual_write` / `false`; local dev and CI pin explicit values via+ // .env.dev*.example, so these defaults only apply to bare deployments.LANGFUSE_MIGRATION_V4_WRITE_MODE: z.enum(["legacy", "dual", "events_only"])- .default("legacy"),+ .default("events_only"),LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR: z.enum(["dual_write", "direct"])- .default("dual_write"),+ .default("direct"),LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN: z.enum(["true", "false"])- .default("false"),+ .default("true"),// Background-migration env gates. Names share the LANGFUSE_BACKGROUND_MIGRATION_// prefix so the BackgroundMigrationManager can discover them by scanning env// keys; each gates one or more rows in the background_migrations table via- // `args.envGate`. Default to "false" so dormant migrations only run when the- // operator explicitly opts in.+ // `args.envGate`. The historic backfill defaults on in v4 (it is a no-op for+ // net-new deployments with no legacy data); the pid/tid sorting-table cleanup+ // stays opt-in so its intermediate artifacts are only dropped once the+ // operator confirms the backfill succeeded.LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL: z.enum(["true", "false"])- .default("false"),+ .default("true"),LANGFUSE_BACKGROUND_MIGRATION_V4_DROP_PID_TID_SORTING_TABLES: z.enum(["true", "false"]).default("false"),diff --git a/worker/src/features/health/index.ts b/worker/src/features/health/index.tsindex e6deb7072f..4706211447 100644--- a/worker/src/features/health/index.ts+++ b/worker/src/features/health/index.ts@@ -2,7 +2,7 @@ import { prisma } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";import { Response } from "express";-import { env } from "../../env";+import { env, v4WritesToEventsTable } from "../../env";import {getLastProcessedPartition,getLastRunStartedAt,@@ -25,9 +25,12 @@ export type EventPropagationHealth = {stuck: boolean;};+// Must mirror the registration guard in worker/src/app.ts: the propagation+// worker runs for every write mode that targets events_full (dual AND+// events_only), so the liveness gate has to stay active for both.const isEventPropagationEnabled = (): boolean =>env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true" &&- env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "dual";+ v4WritesToEventsTable(env);/*** `stuck` is intentionally only true when we have a reading that exceeds the