🪢 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)!: drop superseded Postgres and ClickHouse tables (#15369)
Steffen Schmitz340c3c850770
diff --git a/packages/shared/clickhouse/migrations/clustered/0044_drop_event_log.down.sql b/packages/shared/clickhouse/migrations/clustered/0044_drop_event_log.down.sqlnew file mode 100644index 0000000000..f894ad58fe--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0044_drop_event_log.down.sql@@ -0,0 +1,21 @@+-- WARNING: This recreates the table structure only. Any data held in+-- event_log before the up migration dropped it is NOT restored.+CREATE TABLE IF NOT EXISTS event_log ON CLUSTER default+(+ `id` String,+ `project_id` String,+ `entity_type` String,+ `entity_id` String,+ `event_id` Nullable(String),++ `bucket_name` String,+ `bucket_path` String,++ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now()+) ENGINE = MergeTree()+ ORDER BY (+ project_id,+ entity_type,+ entity_id+ );diff --git a/packages/shared/clickhouse/migrations/clustered/0044_drop_event_log.up.sql b/packages/shared/clickhouse/migrations/clustered/0044_drop_event_log.up.sqlnew file mode 100644index 0000000000..3682d6d29c--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0044_drop_event_log.up.sql@@ -0,0 +1,5 @@+-- The event_log table was superseded by blob_storage_file_log. Its contents+-- were copied over by the 20250417_1737_migrate_event_log_to_blob_storage+-- background migration, which must have completed (on the latest v3 release)+-- before upgrading to v4.+DROP TABLE IF EXISTS event_log ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/clustered/0045_drop_project_environments.down.sql b/packages/shared/clickhouse/migrations/clustered/0045_drop_project_environments.down.sqlnew file mode 100644index 0000000000..a1de329190--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0045_drop_project_environments.down.sql@@ -0,0 +1,9 @@+-- WARNING: This recreates the table structure only. Any data held in+-- project_environments before the up migration dropped it is NOT restored,+-- and the materialized views that used to feed the table were already dropped+-- by 0027_drop_project_environments_mvs, so it stays empty.+CREATE TABLE IF NOT EXISTS project_environments ON CLUSTER default (+ `project_id` String,+ `environments` SimpleAggregateFunction(groupUniqArrayArray, Array(String))+) ENGINE = ReplicatedAggregatingMergeTree+ORDER BY (project_id);diff --git a/packages/shared/clickhouse/migrations/clustered/0045_drop_project_environments.up.sql b/packages/shared/clickhouse/migrations/clustered/0045_drop_project_environments.up.sqlnew file mode 100644index 0000000000..25cb10b8a0--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0045_drop_project_environments.up.sql@@ -0,0 +1,5 @@+-- The project_environments table has been unused since+-- 0027_drop_project_environments_mvs removed the materialized views feeding+-- it. getEnvironmentsForProject reads distinct environments from the tracing+-- and scores tables directly.+DROP TABLE IF EXISTS project_environments ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/clustered/0046_drop_dataset_run_items.down.sql b/packages/shared/clickhouse/migrations/clustered/0046_drop_dataset_run_items.down.sqlnew file mode 100644index 0000000000..3291a7b3ad--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0046_drop_dataset_run_items.down.sql@@ -0,0 +1,38 @@+-- WARNING: This recreates the table structure only. Any data held in+-- dataset_run_items before the up migration dropped it is NOT restored.+CREATE TABLE IF NOT EXISTS dataset_run_items ON CLUSTER default (+ -- primary identifiers+ `id` String,+ `project_id` String,+ `dataset_run_id` String,+ `dataset_item_id` String,+ `dataset_id` String,+ `trace_id` String,+ `observation_id` Nullable(String),++ -- error field+ `error` Nullable(String),++ -- timestamps+ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now(),++ -- denormalized immutable dataset run fields+ `dataset_run_name` String,+ `dataset_run_description` Nullable(String),+ `dataset_run_metadata` Map(LowCardinality(String), String),+ `dataset_run_created_at` DateTime64(3),++ -- denormalized dataset item fields (mutable, but snapshots are relevant)+ `dataset_item_input` Nullable(String) CODEC(ZSTD(3)), -- json+ `dataset_item_expected_output` Nullable(String) CODEC(ZSTD(3)), -- json+ `dataset_item_metadata` Map(LowCardinality(String), String),++ -- clickhouse engine fields+ `event_ts` DateTime64(3),+ `is_deleted` UInt8,++ -- For dataset item lookups+ INDEX idx_dataset_item dataset_item_id TYPE bloom_filter(0.001) GRANULARITY 1,+) ENGINE = ReplacingMergeTree(event_ts, is_deleted)+ORDER BY (project_id, dataset_id, dataset_run_id, id);diff --git a/packages/shared/clickhouse/migrations/clustered/0046_drop_dataset_run_items.up.sql b/packages/shared/clickhouse/migrations/clustered/0046_drop_dataset_run_items.up.sqlnew file mode 100644index 0000000000..353b69e3b4--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0046_drop_dataset_run_items.up.sql@@ -0,0 +1,4 @@+-- The dataset_run_items table was superseded by dataset_run_items_rmt+-- (created in 0024). All ingestion writes, reads and deletes target the+-- _rmt table, so this table has been frozen since the cutover.+DROP TABLE IF EXISTS dataset_run_items ON CLUSTER default;diff --git a/packages/shared/clickhouse/migrations/unclustered/0044_drop_event_log.down.sql b/packages/shared/clickhouse/migrations/unclustered/0044_drop_event_log.down.sqlnew file mode 100644index 0000000000..939378be98--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0044_drop_event_log.down.sql@@ -0,0 +1,21 @@+-- WARNING: This recreates the table structure only. Any data held in+-- event_log before the up migration dropped it is NOT restored.+CREATE TABLE IF NOT EXISTS event_log+(+ `id` String,+ `project_id` String,+ `entity_type` String,+ `entity_id` String,+ `event_id` Nullable(String),++ `bucket_name` String,+ `bucket_path` String,++ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now()+) ENGINE = MergeTree()+ ORDER BY (+ project_id,+ entity_type,+ entity_id+ );diff --git a/packages/shared/clickhouse/migrations/unclustered/0044_drop_event_log.up.sql b/packages/shared/clickhouse/migrations/unclustered/0044_drop_event_log.up.sqlnew file mode 100644index 0000000000..1fdc2a46fc--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0044_drop_event_log.up.sql@@ -0,0 +1,5 @@+-- The event_log table was superseded by blob_storage_file_log. Its contents+-- were copied over by the 20250417_1737_migrate_event_log_to_blob_storage+-- background migration, which must have completed (on the latest v3 release)+-- before upgrading to v4.+DROP TABLE IF EXISTS event_log;diff --git a/packages/shared/clickhouse/migrations/unclustered/0045_drop_project_environments.down.sql b/packages/shared/clickhouse/migrations/unclustered/0045_drop_project_environments.down.sqlnew file mode 100644index 0000000000..fdf1f4db39--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0045_drop_project_environments.down.sql@@ -0,0 +1,9 @@+-- WARNING: This recreates the table structure only. Any data held in+-- project_environments before the up migration dropped it is NOT restored,+-- and the materialized views that used to feed the table were already dropped+-- by 0027_drop_project_environments_mvs, so it stays empty.+CREATE TABLE IF NOT EXISTS project_environments (+ `project_id` String,+ `environments` SimpleAggregateFunction(groupUniqArrayArray, Array(String))+) ENGINE = AggregatingMergeTree+ORDER BY (project_id);diff --git a/packages/shared/clickhouse/migrations/unclustered/0045_drop_project_environments.up.sql b/packages/shared/clickhouse/migrations/unclustered/0045_drop_project_environments.up.sqlnew file mode 100644index 0000000000..18a2795bc0--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0045_drop_project_environments.up.sql@@ -0,0 +1,5 @@+-- The project_environments table has been unused since+-- 0027_drop_project_environments_mvs removed the materialized views feeding+-- it. getEnvironmentsForProject reads distinct environments from the tracing+-- and scores tables directly.+DROP TABLE IF EXISTS project_environments;diff --git a/packages/shared/clickhouse/migrations/unclustered/0046_drop_dataset_run_items.down.sql b/packages/shared/clickhouse/migrations/unclustered/0046_drop_dataset_run_items.down.sqlnew file mode 100644index 0000000000..88a8e3d72d--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0046_drop_dataset_run_items.down.sql@@ -0,0 +1,38 @@+-- WARNING: This recreates the table structure only. Any data held in+-- dataset_run_items before the up migration dropped it is NOT restored.+CREATE TABLE IF NOT EXISTS dataset_run_items (+ -- primary identifiers+ `id` String,+ `project_id` String,+ `dataset_run_id` String,+ `dataset_item_id` String,+ `dataset_id` String,+ `trace_id` String,+ `observation_id` Nullable(String),++ -- error field+ `error` Nullable(String),++ -- timestamps+ `created_at` DateTime64(3) DEFAULT now(),+ `updated_at` DateTime64(3) DEFAULT now(),++ -- denormalized immutable dataset run fields+ `dataset_run_name` String,+ `dataset_run_description` Nullable(String),+ `dataset_run_metadata` Map(LowCardinality(String), String),+ `dataset_run_created_at` DateTime64(3),++ -- denormalized dataset item fields (mutable, but snapshots are relevant)+ `dataset_item_input` Nullable(String) CODEC(ZSTD(3)), -- json+ `dataset_item_expected_output` Nullable(String) CODEC(ZSTD(3)), -- json+ `dataset_item_metadata` Map(LowCardinality(String), String),++ -- clickhouse engine fields+ `event_ts` DateTime64(3),+ `is_deleted` UInt8,++ -- For dataset item lookups+ INDEX idx_dataset_item dataset_item_id TYPE bloom_filter(0.001) GRANULARITY 1,+) ENGINE = ReplacingMergeTree(event_ts, is_deleted)+ORDER BY (project_id, dataset_id, dataset_run_id, id);diff --git a/packages/shared/clickhouse/migrations/unclustered/0046_drop_dataset_run_items.up.sql b/packages/shared/clickhouse/migrations/unclustered/0046_drop_dataset_run_items.up.sqlnew file mode 100644index 0000000000..5e05c6cec7--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0046_drop_dataset_run_items.up.sql@@ -0,0 +1,4 @@+-- The dataset_run_items table was superseded by dataset_run_items_rmt+-- (created in 0024). All ingestion writes, reads and deletes target the+-- _rmt table, so this table has been frozen since the cutover.+DROP TABLE IF EXISTS dataset_run_items;diff --git a/packages/shared/prisma/migrations/20260723124010_drop_dataset_run_items_table/migration.sql b/packages/shared/prisma/migrations/20260723124010_drop_dataset_run_items_table/migration.sqlnew file mode 100644index 0000000000..710d19f915--- /dev/null+++ b/packages/shared/prisma/migrations/20260723124010_drop_dataset_run_items_table/migration.sql@@ -0,0 +1,16 @@+-- The legacy dataset_run_items table is superseded by the ClickHouse+-- dataset_run_items_rmt table. Its contents were copied over by the+-- 20250814_1001_migrate_dataset_run_items_rmt_pg_to_ch background migration,+-- which must have completed (on the latest v3 release) before upgrading to v4.+DROP TABLE IF EXISTS "dataset_run_items";++-- Remove the background migrations whose source tables are dropped in v4+-- (dataset_run_items here, event_log in ClickHouse migration 0044). Their+-- worker scripts are deleted alongside this migration, so leftover unfinished+-- rows would make the BackgroundMigrationManager fail to resolve the script.+DELETE FROM "background_migrations"+WHERE "name" IN (+ '20250417_1737_migrate_event_log_to_blob_storage',+ '20250731_1001_migrate_dataset_run_items_pg_to_ch',+ '20250814_1001_migrate_dataset_run_items_rmt_pg_to_ch'+);diff --git a/packages/shared/prisma/migrations/20260723150000_drop_legacy_tracing_tables/migration.sql b/packages/shared/prisma/migrations/20260723150000_drop_legacy_tracing_tables/migration.sqlnew file mode 100644index 0000000000..071599279f--- /dev/null+++ b/packages/shared/prisma/migrations/20260723150000_drop_legacy_tracing_tables/migration.sql@@ -0,0 +1,24 @@+-- The traces, observations and scores tables were superseded by their+-- ClickHouse counterparts in v3. Their contents were copied over by the+-- 20241024_* background migrations, which must have completed (on the latest+-- v3 release) before upgrading to v4.+DROP TABLE IF EXISTS "traces";+DROP TABLE IF EXISTS "observations";+DROP TABLE IF EXISTS "scores";++-- These enum types were only used by the dropped tables.+DROP TYPE IF EXISTS "ObservationType";+DROP TYPE IF EXISTS "ObservationLevel";+DROP TYPE IF EXISTS "ScoreSource";++-- Remove the background migrations whose source tables are dropped above.+-- Their worker scripts are deleted alongside this migration, so leftover+-- unfinished rows would make the BackgroundMigrationManager fail to resolve+-- the script.+DELETE FROM "background_migrations"+WHERE "name" IN (+ '20241024_1216_add_generations_cost_backfill',+ '20241024_1730_migrate_traces_from_pg_to_ch',+ '20241024_1737_migrate_observations_from_pg_to_ch',+ '20241024_1738_migrate_scores_from_pg_to_ch'+);diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 00985ca964..e52ae974a0 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -160,9 +160,6 @@ model Project {annotationQueue AnnotationQueue[]annotationQueueItem AnnotationQueueItem[]Media Media[]- LegacyTrace LegacyPrismaTrace[]- LegacyObservation LegacyPrismaObservation[]- LegacyScore LegacyPrismaScore[]PromptDependency PromptDependency[]LlmSchema LlmSchema[]LlmTool LlmTool[]@@ -441,154 +438,6 @@ model TraceSession {@@map("trace_sessions")}-model LegacyPrismaTrace {- id String @id @default(cuid())- externalId String? @map("external_id")- timestamp DateTime @default(now())- name String?- userId String? @map("user_id")- metadata Json?- release String?- version String?- projectId String @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- public Boolean @default(false)- bookmarked Boolean @default(false)- tags String[] @default([])- input Json?- output Json?- sessionId String? @map("session_id")- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")-- @@index([projectId, timestamp])- @@index([sessionId])- @@index([name])- @@index([userId])- @@index([id, userId])- @@index(timestamp)- @@index(createdAt)- @@index([tags(ops: ArrayOps)], type: Gin)- @@map("traces")-}--model LegacyPrismaObservation {- id String @id @default(cuid())- traceId String? @map("trace_id")- projectId String @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- type LegacyPrismaObservationType- startTime DateTime @default(now()) @map("start_time")- endTime DateTime? @map("end_time")- name String?- metadata Json?- parentObservationId String? @map("parent_observation_id")- level LegacyPrismaObservationLevel @default(DEFAULT)- statusMessage String? @map("status_message")- version String?- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")- model String? // user-provided model attribute- internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated- internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time- modelParameters Json?- input Json?- output Json?- promptTokens Int @default(0) @map("prompt_tokens")- completionTokens Int @default(0) @map("completion_tokens")- totalTokens Int @default(0) @map("total_tokens")- unit String?- // User provided cost at ingestion- inputCost Decimal? @map("input_cost")- outputCost Decimal? @map("output_cost")- totalCost Decimal? @map("total_cost")- // Calculated cost- calculatedInputCost Decimal? @map("calculated_input_cost")- calculatedOutputCost Decimal? @map("calculated_output_cost")- calculatedTotalCost Decimal? @map("calculated_total_cost")- completionStartTime DateTime? @map("completion_start_time")- promptId String? @map("prompt_id") // no fk constraint, prompt can be deleted-- @@unique([id, projectId])- @@index([projectId, internalModel, startTime, unit])- @@index([traceId, projectId, type, startTime])- @@index([traceId, projectId, startTime])- @@index([type])- @@index(startTime)- @@index(createdAt)- @@index(model)- @@index(internalModel)- @@index([projectId, promptId])- @@index(promptId)- @@index([projectId, startTime, type])- @@map("observations")-}--enum LegacyPrismaObservationType {- SPAN- EVENT- GENERATION- AGENT- TOOL- CHAIN- RETRIEVER- EVALUATOR- EMBEDDING- GUARDRAIL-- @@map("ObservationType")-}--enum LegacyPrismaObservationLevel {- DEBUG- DEFAULT- WARNING- ERROR-- @@map("ObservationLevel")-}--model LegacyPrismaScore {- id String @id @default(cuid())- timestamp DateTime @default(now())- projectId String @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- name String- value Float? // always defined if data type is NUMERIC or BOOLEAN, optional for CATEGORICAL- source LegacyPrismaScoreSource- authorUserId String? @map("author_user_id")- comment String?- traceId String @map("trace_id")- observationId String? @map("observation_id")- configId String? @map("config_id")- stringValue String? @map("string_value") // always defined if data type is CATEGORICAL or BOOLEAN, null for NUMERIC- queueId String? @map("queue_id")- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")- dataType ScoreConfigDataType @default(NUMERIC) @map("data_type")- scoreConfig ScoreConfig? @relation(fields: [configId], references: [id], onDelete: SetNull)-- @@unique([id, projectId]) // used for upserts via prisma- @@index(timestamp)- @@index([value])- @@index([projectId, name])- @@index([authorUserId])- @@index([configId])- @@index([traceId], type: Hash)- @@index([observationId], type: Hash)- @@index([source])- @@index([createdAt])- @@map("scores")-}--enum LegacyPrismaScoreSource {- ANNOTATION- API- EVAL-- @@map("ScoreSource")-}-model ScoreConfig {id String @id @default(cuid())createdAt DateTime @default(now()) @map("created_at")@@ -602,7 +451,6 @@ model ScoreConfig {maxValue Float? @map("max_value")categories Json? @map("categories")description String?- legacyScore LegacyPrismaScore[]@@unique([id, projectId]) // used for upserts via prisma@@index([dataType])@@ -768,7 +616,6 @@ model DatasetRuns {dataset Dataset @relation(fields: [datasetId, projectId], references: [id, projectId], onDelete: Cascade)createdAt DateTime @default(now()) @map("created_at")updatedAt DateTime @default(now()) @updatedAt @map("updated_at")- datasetRunItems DatasetRunItems[]@@id([id, projectId])@@unique([datasetId, projectId, name])@@ -778,27 +625,6 @@ model DatasetRuns {@@map("dataset_runs")}-model DatasetRunItems {- id String @default(cuid())- projectId String @map("project_id")- datasetRunId String @map("dataset_run_id")- datasetRun DatasetRuns @relation(fields: [datasetRunId, projectId], references: [id, projectId], onDelete: Cascade)- datasetItemId String @map("dataset_item_id")- traceId String @map("trace_id")- observationId String? @map("observation_id")- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")-- @@id([id, projectId])- @@index([datasetRunId], type: Hash)- @@index([datasetItemId], type: Hash)- @@index([observationId], type: Hash)- @@index([traceId])- @@index([createdAt])- @@index([updatedAt])- @@map("dataset_run_items")-}-model Comment {id String @id @default(cuid())projectId String @map("project_id")diff --git a/packages/shared/src/server/repositories/blobStorageLog.ts b/packages/shared/src/server/repositories/blobStorageLog.tsindex 1a96a6e771..b4443e0999 100644--- a/packages/shared/src/server/repositories/blobStorageLog.ts+++ b/packages/shared/src/server/repositories/blobStorageLog.ts@@ -1,8 +1,4 @@-import {- commandClickhouse,- queryClickhouse,- queryClickhouseStream,-} from "./clickhouse";+import { queryClickhouse, queryClickhouseStream } from "./clickhouse";import { BlobStorageFileRefRecordReadType } from "./definitions";import { convertDateToClickhouseDateTime } from "../clickhouse/client";@@ -185,73 +181,3 @@ export const getBlobStorageByProjectIdAndTraceIds = (tags: { projectId },});};--// this function is only used for the background migration from event_log to blob_storage_file_log-export const insertIntoS3RefsTableFromEventLog = async (- limit: number,- offset: number,-) => {- const query = `- INSERT INTO blob_storage_file_log- SELECT- id,- project_id,- entity_type,- entity_id,- event_id,- bucket_name,- bucket_path,- created_at,- updated_at,- created_at AS event_ts,- 0 AS is_deleted- FROM event_log- ORDER BY (project_id, entity_type, entity_id, bucket_path) DESC- LIMIT {limit: Int32}- OFFSET {offset: Int32}- `;-- await commandClickhouse({- query,- params: {- limit,- offset,- },- });-};--export const getLastEventLogPrimaryKey = async () => {- const query = `- SELECT project_id, entity_type, entity_id, bucket_path- FROM event_log- ORDER BY (project_id, entity_type, entity_id, bucket_path) ASC- LIMIT 1- `;- const result = await queryClickhouse<{- project_id: string;- entity_type: string;- entity_id: string;- bucket_path: string;- }>({ query });- return result.shift();-};--export const findS3RefsByPrimaryKey = async (primaryKey: {- project_id: string;- entity_type: string;- entity_id: string;- bucket_path: string;-}) => {- const query = `- SELECT *- FROM blob_storage_file_log- WHERE project_id = {project_id: String}- AND entity_type = {entity_type: String}- AND entity_id = {entity_id: String}- AND bucket_path = {bucket_path: String}- `;- return queryClickhouse<BlobStorageFileRefRecordReadType>({- query,- params: primaryKey,- });-};diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex 9ee242a625..99d8cd684c 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -1,6 +1,5 @@import z from "zod";import type { IngestionAttribution } from "../ingestion/ingestionAttribution";-import { UNKNOWN_INGESTION_SDK_VALUE } from "../ingestion/ingestionAttribution";import { DEFAULT_TRACE_ENVIRONMENT } from "../ingestion/types";export const clickhouseStringDateSchema = z@@ -456,198 +455,6 @@ export const convertTraceToStagingObservation = (};};-/**- * Expects a single record from a `select * from traces` query. Must be a raw query to keep original- * column names, not the Prisma mapped names.- */-export const convertPostgresTraceToInsert = (- trace: Record<string, any>,-): TraceRecordInsertType => {- return {- id: trace.id,- timestamp: trace.timestamp?.getTime(),- name: trace.name,- user_id: trace.user_id,- metadata:- typeof trace.metadata === "string"- ? { metadata: trace.metadata }- : Array.isArray(trace.metadata)- ? { metadata: trace.metadata }- : trace.metadata,- environment: trace.environment,- release: trace.release,- version: trace.version,- project_id: trace.project_id,- public: trace.public,- bookmarked: trace.bookmarked,- tags: trace.tags,- input: trace.input ? JSON.stringify(trace.input) : null,- output: trace.output ? JSON.stringify(trace.output) : null,- session_id: trace.session_id,- created_at: trace.created_at?.getTime(),- updated_at: trace.updated_at?.getTime(),- event_ts: trace.timestamp?.getTime(),- is_deleted: 0,- };-};--export const convertPostgresDatasetRunItemToInsert = (- datasetRunItem: Record<string, any>,-): DatasetRunItemRecordInsertType => {- return {- id: datasetRunItem.id,- project_id: datasetRunItem.project_id,- dataset_run_id: datasetRunItem.dataset_run_id,- dataset_item_id: datasetRunItem.dataset_item_id,- dataset_id: datasetRunItem.dataset_id,- trace_id: datasetRunItem.trace_id,- observation_id: datasetRunItem.observation_id,- error: datasetRunItem.error,- created_at: datasetRunItem.created_at?.getTime(),- updated_at: datasetRunItem.updated_at?.getTime(),- // denormalized run data- dataset_run_name: datasetRunItem.dataset_run_name,- dataset_run_description: datasetRunItem.dataset_run_description,- dataset_run_metadata:- typeof datasetRunItem.dataset_run_metadata === "string" ||- typeof datasetRunItem.dataset_run_metadata === "number" ||- typeof datasetRunItem.dataset_run_metadata === "boolean"- ? { metadata: datasetRunItem.dataset_run_metadata }- : Array.isArray(datasetRunItem.dataset_run_metadata)- ? { metadata: datasetRunItem.dataset_run_metadata }- : (datasetRunItem.dataset_run_metadata ?? {}),- dataset_run_created_at: datasetRunItem.dataset_run_created_at?.getTime(),- // denormalized item data- dataset_item_input: JSON.stringify(datasetRunItem.dataset_item_input),- dataset_item_expected_output: JSON.stringify(- datasetRunItem.dataset_item_expected_output,- ),- dataset_item_metadata:- typeof datasetRunItem.dataset_item_metadata === "string" ||- typeof datasetRunItem.dataset_item_metadata === "number" ||- typeof datasetRunItem.dataset_item_metadata === "boolean"- ? { metadata: datasetRunItem.dataset_item_metadata }- : Array.isArray(datasetRunItem.dataset_item_metadata)- ? { metadata: datasetRunItem.dataset_item_metadata }- : (datasetRunItem.dataset_item_metadata ?? {}),- event_ts: datasetRunItem.created_at?.getTime(),- is_deleted: 0,- };-};--/**- * Expects a single record from a- * `select o.*,- * o."modelParameters" as model_parameters,- * p.name as prompt_name,- * p.version as prompt_version- * from observations o- * LEFT JOIN prompts p ON p.id = o.prompt_id`- * query. Must be a raw query to keep original- * column names, not the Prisma mapped names.- */-export const convertPostgresObservationToInsert = (- observation: Record<string, any>,-): ObservationRecordInsertType => {- return {- id: observation.id,- trace_id: observation.trace_id,- project_id: observation.project_id,- type: observation.type,- parent_observation_id: observation.parent_observation_id,- environment: observation.environment,- start_time: observation.start_time?.getTime(),- end_time: observation.end_time?.getTime(),- name: observation.name,- metadata:- typeof observation.metadata === "string"- ? { metadata: observation.metadata }- : Array.isArray(observation.metadata)- ? { metadata: observation.metadata }- : observation.metadata,- level: observation.level,- status_message: observation.status_message,- version: observation.version,- input: observation.input ? JSON.stringify(observation.input) : null,- output: observation.output ? JSON.stringify(observation.output) : null,- provided_model_name: observation.model,- internal_model_id: observation.internal_model_id,- model_parameters: observation.model_parameters- ? JSON.stringify(observation.model_parameters)- : null,- provided_usage_details: {},- usage_details: {- input: observation.prompt_tokens >= 0 ? observation.prompt_tokens : null,- output:- observation.completion_tokens >= 0- ? observation.completion_tokens- : null,- total: observation.total_tokens >= 0 ? observation.total_tokens : null,- },- provided_cost_details: {- input: observation.input_cost?.toNumber() ?? null,- output: observation.output_cost?.toNumber() ?? null,- total: observation.total_cost?.toNumber() ?? null,- },- cost_details: {- input: observation.calculated_input_cost?.toNumber() ?? null,- output: observation.calculated_output_cost?.toNumber() ?? null,- total: observation.calculated_total_cost?.toNumber() ?? null,- },- total_cost: observation.calculated_total_cost?.toNumber() ?? null,- completion_start_time: observation.completion_start_time?.getTime(),- prompt_id: observation.prompt_id,- prompt_name: observation.prompt_name,- prompt_version: observation.prompt_version,- // Tool fields - Postgres observations don't have persisted tools- tool_definitions: undefined,- tool_calls: undefined,- tool_call_names: undefined,- created_at: observation.created_at?.getTime(),- updated_at: observation.updated_at?.getTime(),- event_ts: observation.start_time?.getTime(),- is_deleted: 0,- };-};--/**- * Expects a single record from a `select * from scores` query. Must be a raw query to keep original- * column names, not the Prisma mapped names.- */-export const convertPostgresScoreToInsert = (- score: Record<string, any>,-): ScoreRecordInsertType => {- return {- id: score.id,- timestamp: score.timestamp?.getTime(),- project_id: score.project_id,- trace_id: score.trace_id,- session_id: null,- dataset_run_id: null,- observation_id: score.observation_id,- environment: score.environment,- name: score.name,- value: score.value,- source: score.source,- comment: score.comment,- metadata: score.metadata ?? {},- author_user_id: score.author_user_id,- config_id: score.config_id,- data_type: score.data_type,- string_value: score.string_value,- long_string_value: "",- queue_id: score.queue_id,- execution_trace_id: null, // Postgres scores do not have eval execution traces- ingestion_api_key: "",- ingestion_sdk_name: UNKNOWN_INGESTION_SDK_VALUE,- ingestion_sdk_version: UNKNOWN_INGESTION_SDK_VALUE,- created_at: score.created_at?.getTime(),- updated_at: score.updated_at?.getTime(),- event_ts: score.timestamp?.getTime(),- is_deleted: 0,- };-};-export const eventRecordBaseSchema = z.object({// Identifiersorg_id: z.string().nullish(),diff --git a/web/src/__tests__/server/repositories/environment-repository.servertest.ts b/web/src/__tests__/server/repositories/environment-repository.servertest.tsindex 0cde2ec2cc..0938c389bf 100644--- a/web/src/__tests__/server/repositories/environment-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/environment-repository.servertest.ts@@ -32,7 +32,7 @@ describe("Clickhouse Project Repository Test", () => {expect(environments[0].environment).toEqual("default");});- it("should return environment from project_environments table after new trace was inserted", async () => {+ it("should return environments from the traces table after new traces were inserted", async () => {const projectId = randomUUID();const environmentId1 = randomUUID();const environmentId2 = randomUUID();diff --git a/worker/src/backgroundMigrations/addGenerationsCostBackfill.ts b/worker/src/backgroundMigrations/addGenerationsCostBackfill.tsdeleted file mode 100644index b1a0c48fee..0000000000--- a/worker/src/backgroundMigrations/addGenerationsCostBackfill.ts+++ /dev/null@@ -1,234 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import { logger } from "@langfuse/shared/src/server";-import { parseArgs } from "node:util";-import { prisma, Prisma } from "@langfuse/shared/src/db";--type StatementTimeout = {- statement_timeout: string;-};--async function updateStatementTimeout(- newTimeout: string,- previousTimeout: any,-) {- const [{ statement_timeout: previousTimeoutRead }] = await prisma.$queryRaw<- StatementTimeout[]- >(Prisma.sql`SHOW statement_timeout;`);- logger.info(`Current statement_timeout ${previousTimeoutRead}`);- if (!previousTimeoutRead || previousTimeoutRead === newTimeout) {- // If the statement_timeout is already set to 19 minutes, assume it was set by this script and reset it to 2 minutes- previousTimeout = "2min";- } else {- previousTimeout = previousTimeoutRead;- }- await prisma.$executeRawUnsafe(`SET statement_timeout = '${newTimeout}';`);- logger.info(`Updated statement_timeout to ${newTimeout}`);- return previousTimeout;-}--async function addTemporaryColumnIfNotExists() {- const columnExists = await prisma.$queryRaw<{ column_exists: boolean }[]>(- Prisma.sql`- SELECT EXISTS (- SELECT 1- FROM information_schema.columns- WHERE table_name = 'observations'- AND column_name = 'tmp_has_calculated_cost'- ) AS column_exists;- `,- );- if (!columnExists[0]?.column_exists) {- await prisma.$executeRaw`ALTER TABLE observations ADD COLUMN tmp_has_calculated_cost BOOLEAN DEFAULT FALSE;`;- logger.info("Added temporary column tmp_has_calculated_cost");- } else {- logger.info(- "Temporary column tmp_has_calculated_cost already exists. Continuing...",- );- }-}--export default class AddGenerationsCostBackfill implements IBackgroundMigration {- private isAborted = false;-- async validate(- _args: Record<string, unknown>,- ): Promise<{ valid: boolean; invalidReason: string | undefined }> {- // No validation to be done- return { valid: true, invalidReason: undefined };- }-- async run(args: Record<string, unknown>): Promise<void> {- logger.info(- `Running AddGenerationsCostBackfill migration with ${JSON.stringify(args)}`,- );- let previousTimeout;-- const maxRowsToProcess = Number(args.maxRowsToProcess ?? Infinity);- const batchSize = Number(args.batchSize ?? 1000);- let currentDateCutoff = args.maxDate ?? new Date().toISOString();-- try {- // Set the statement timeout- const newTimeout = "19min";- previousTimeout = await updateStatementTimeout(- newTimeout,- previousTimeout,- );-- // Add tracking column- await addTemporaryColumnIfNotExists();-- let totalRowsProcessed = 0;- while (!this.isAborted && totalRowsProcessed < maxRowsToProcess) {- const batchUpdate = await prisma.$queryRaw<- { start_time: Date }[]- >(Prisma.sql`- WITH batch AS (- SELECT o.id,- o.start_time,- o.prompt_tokens,- o.completion_tokens,- o.total_tokens,- o.input_cost,- o.output_cost,- o.total_cost,- m.id AS model_id,- m.input_price,- m.output_price,- m.total_price- FROM observations o- LEFT JOIN LATERAL (- SELECT models.id,- models.input_price,- models.output_price,- models.total_price- FROM models- WHERE (models.project_id = o.project_id OR models.project_id IS NULL)- AND models.model_name = o.internal_model- AND (models.start_date < o.start_time OR models.start_date IS NULL)- AND o.unit = models.unit- ORDER BY models.project_id, models.start_date DESC NULLS LAST- LIMIT 1- ) m ON true- WHERE start_time <= ${currentDateCutoff}::TIMESTAMP WITH TIME ZONE AT TIME ZONE 'UTC'- AND (internal_model IS NOT NULL- OR input_cost IS NOT NULL- OR output_cost IS NOT NULL- OR total_cost IS NOT NULL)- ORDER BY start_time DESC- LIMIT ${batchSize}- ),- updated_batch AS (- UPDATE observations o- SET- calculated_input_cost =- CASE- WHEN batch.input_cost IS NULL AND batch.output_cost IS NULL AND batch.total_cost IS NULL- THEN batch.prompt_tokens::numeric * batch.input_price- ELSE batch.input_cost- END,- calculated_output_cost =- CASE- WHEN batch.input_cost IS NULL AND batch.output_cost IS NULL AND batch.total_cost IS NULL- THEN batch.completion_tokens::numeric * batch.output_price- ELSE batch.output_cost- END,- calculated_total_cost =- CASE- WHEN batch.input_cost IS NULL AND batch.output_cost IS NULL AND batch.total_cost IS NULL- THEN- CASE- WHEN batch.total_price IS NOT NULL AND batch.total_tokens IS NOT NULL THEN batch.total_price * batch.total_tokens::numeric- ELSE batch.prompt_tokens::numeric * batch.input_price + batch.completion_tokens::numeric * batch.output_price- END- ELSE batch.total_cost- END,- internal_model_id = batch.model_id,- tmp_has_calculated_cost = TRUE- FROM batch- WHERE o.id = batch.id- RETURNING o.id- )- -- Get the last id of the updated batch- SELECT start_time FROM batch LIMIT 1 OFFSET ${batchSize - 1};- `);-- if (!batchUpdate[0]?.start_time) {- logger.info(- `No more rows to process, breaking loop after ${totalRowsProcessed} rows processed.`,- );- break;- }-- currentDateCutoff = batchUpdate[0]?.start_time.toISOString();- totalRowsProcessed += batchSize;-- logger.info(- `Total rows processed after increment: ${totalRowsProcessed} rows`,- );- if (maxRowsToProcess && totalRowsProcessed >= maxRowsToProcess) {- logger.info(- `Max rows to process reached: ${maxRowsToProcess.toLocaleString()}, breaking loop.`,- );-- break;- }- }-- if (this.isAborted) {- logger.info(- `Backfill aborted after processing ${totalRowsProcessed} rows. Skipping cleanup.`,- );- return;- }-- await prisma.$executeRaw`ALTER TABLE observations DROP COLUMN IF EXISTS tmp_has_calculated_cost;`;- logger.info(- `Backfill completed after processing ${totalRowsProcessed} rows`,- );- } catch (e) {- logger.error(`Error backfilling costs: ${e}`, e);- throw e;- } finally {- await prisma.$executeRawUnsafe(- `SET statement_timeout = '${previousTimeout}';`,- );- logger.info(`Reset statement_timeout to ${previousTimeout}`);- }- }-- async abort(): Promise<void> {- logger.info(`Aborting AddGenerationsCostBackfill migration`);- this.isAborted = true;- }-}--async function main() {- const args = parseArgs({- options: {- batchSize: { type: "string", short: "b", default: "1000" },- maxRowsToProcess: { type: "string", short: "r", default: "Infinity" },- maxDate: {- type: "string",- short: "d",- default: new Date().toISOString(),- },- },- });-- const migration = new AddGenerationsCostBackfill();- await migration.validate(args.values);- await migration.run(args.values);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouse.ts b/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouse.tsdeleted file mode 100644index 44a09a1348..0000000000--- a/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouse.ts+++ /dev/null@@ -1,60 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import { logger } from "@langfuse/shared/src/server";-import { env } from "../env";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table-// In this case it is not used as we will skip this migration and run the RMT migration instead-// const backgroundMigrationId = "8d47f91b-3e5c-4a26-9f85-c12d6e4b9a3d";--export default class MigrateDatasetRunItemsFromPostgresToClickhouse implements IBackgroundMigration {- async validate(): 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",- };- }-- // Return true as we will skip this migration and run the RMT migration instead- return { valid: true, invalidReason: undefined };- }-- async run(): Promise<void> {- logger.info(- `Migration of dataset run items from postgres to clickhouse skipped as we will run the RMT migration instead`,- );- }-- async abort(): Promise<void> {- logger.info(- `Aborting migration of dataset run items from Postgres to clickhouse`,- );- }-}--async function main() {- const migration = new MigrateDatasetRunItemsFromPostgresToClickhouse();- await migration.validate();- await migration.run();-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`, error);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouseRmt.ts b/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouseRmt.tsdeleted file mode 100644index a7c6db4bf7..0000000000--- a/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouseRmt.ts+++ /dev/null@@ -1,256 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- buildClickHouseLogComment,- clickhouseClient,- convertPostgresDatasetRunItemToInsert,- logger,-} from "@langfuse/shared/src/server";-import { parseArgs } from "node:util";-import { prisma, Prisma } from "@langfuse/shared/src/db";-import { env } from "../env";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table-const backgroundMigrationId = "9f32e84c-7b1d-4f59-a803-d67ae5c9b2e8";--export default class MigrateDatasetRunItemsFromPostgresToClickhouseRmt 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 ClickHouse dataset_run_items_rmt table exists- const tables = await clickhouseClient().query({- query: "SHOW TABLES",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route:- "background-migration.migrateDatasetRunItemsFromPostgresToClickhouseRmt",- }),- },- });- const tableNames = (await tables.json()).data as { name: string }[];- if (!tableNames.some((r) => r.name === "dataset_run_items_rmt")) {- // Retry if the table does not exist as this may mean migrations are still pending- if (attempts > 0) {- logger.info(- `ClickHouse dataset_run_items_rmt table does not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);- });- }-- // If all retries are exhausted, return as invalid- return {- valid: false,- invalidReason: "ClickHouse dataset_run_items_rmt table does not exist",- };- }-- return { valid: true, invalidReason: undefined };- }-- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- logger.info(- `Migrating dataset run items from postgres to clickhouse with ${JSON.stringify(args)}`,- );-- // @ts-ignore- const initialMigrationState: { state: { maxDate: string | undefined } } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const maxRowsToProcess = Number(args.maxRowsToProcess ?? Infinity);- const batchSize = Number(args.batchSize ?? 1000);- const maxDate = initialMigrationState.state?.maxDate- ? new Date(initialMigrationState.state.maxDate)- : new Date((args.maxDate as string) ?? new Date());-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: { maxDate } },- });-- let processedRows = 0;- while (- !this.isAborted &&- !this.isFinished &&- processedRows < maxRowsToProcess- ) {- const fetchStart = Date.now();-- // @ts-ignore- const migrationState: { state: { maxDate: string } } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const datasetRunItems = await prisma.$queryRaw<- Array<Record<string, any>>- >(Prisma.sql`- WITH latest_dataset_items AS (- SELECT DISTINCT ON (id, project_id)- id,- project_id,- dataset_id,- input,- expected_output,- metadata,- created_at,- valid_from,- is_deleted- FROM dataset_items- WHERE valid_to IS NULL- ORDER BY id, project_id, valid_from DESC -- Pick the most recent version- )- SELECT- dri.id as id,- dri.project_id as project_id,- dri.dataset_run_id as dataset_run_id,- dri.dataset_item_id as dataset_item_id,- dri.trace_id as trace_id,- dri.observation_id as observation_id,- dri.created_at as created_at,- dri.updated_at as updated_at,-- -- Denormalized dataset run fields- dr.name as dataset_run_name,- dr.description as dataset_run_description,- dr.metadata as dataset_run_metadata,- dr.created_at as dataset_run_created_at,-- -- Denormalized dataset item fields- ldi.input as dataset_item_input,- ldi.expected_output as dataset_item_expected_output,- ldi.metadata as dataset_item_metadata,-- -- Dataset ID- d.id as dataset_id-- FROM dataset_run_items dri- JOIN dataset_runs dr ON dri.dataset_run_id = dr.id- JOIN latest_dataset_items ldi ON dri.dataset_item_id = ldi.id AND dri.project_id = ldi.project_id- JOIN datasets d ON ldi.dataset_id = d.id- WHERE dri.created_at <= ${new Date(migrationState.state.maxDate)}- AND (ldi.is_deleted IS NULL OR ldi.is_deleted = false)- ORDER BY dri.created_at DESC- LIMIT ${batchSize};- `);- if (datasetRunItems.length === 0) {- logger.info("No more dataset run items to migrate. Exiting...");- break;- }-- logger.info(- `Got ${datasetRunItems.length} records from Postgres in ${Date.now() - fetchStart}ms`,- );-- const insertStart = Date.now();- await clickhouseClient().insert({- table: "dataset_run_items_rmt",- values: datasetRunItems.map(convertPostgresDatasetRunItemToInsert),- format: "JSONEachRow",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route:- "background-migration.migrateDatasetRunItemsFromPostgresToClickhouseRmt",- }),- },- });-- logger.info(- `Inserted ${datasetRunItems.length} dataset run items into Clickhouse in ${Date.now() - insertStart}ms`,- );-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: {- state: {- maxDate: new Date(- datasetRunItems[datasetRunItems.length - 1].created_at,- ),- },- },- });-- if (datasetRunItems.length < batchSize) {- logger.info("No more dataset run items to migrate. Exiting...");- this.isFinished = true;- }-- processedRows += datasetRunItems.length;- logger.info(- `Processed batch in ${Date.now() - fetchStart}ms. Oldest record in batch: ${new Date(datasetRunItems[datasetRunItems.length - 1].created_at).toISOString()}`,- );- }-- if (this.isAborted) {- logger.info(- `Migration of dataset run items from Postgres to Clickhouse aborted after processing ${processedRows} rows. Skipping cleanup.`,- );- return;- }-- logger.info(- `Finished migration of dataset run items from Postgres to Clickhouse in ${Date.now() - start}ms`,- );- }-- async abort(): Promise<void> {- logger.info(- `Aborting migration of dataset run items from Postgres to clickhouse`,- );- this.isAborted = true;- }-}--async function main() {- const args = parseArgs({- options: {- batchSize: { type: "string", short: "b", default: "1000" },- maxRowsToProcess: { type: "string", short: "r", default: "Infinity" },- maxDate: {- type: "string",- short: "d",- default: new Date().toISOString(),- },- },- });-- const migration = new MigrateDatasetRunItemsFromPostgresToClickhouseRmt();- await migration.validate(args.values);- await migration.run(args.values);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`, error);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts b/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.tsdeleted file mode 100644index 30ee276f35..0000000000--- a/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts+++ /dev/null@@ -1,201 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- buildClickHouseLogComment,- clickhouseClient,- findS3RefsByPrimaryKey,- getLastEventLogPrimaryKey,- insertIntoS3RefsTableFromEventLog,- logger,-} from "@langfuse/shared/src/server";-import { parseArgs } from "node:util";-import { prisma } from "@langfuse/shared/src/db";-import { env } from "../env";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table--type MigrationState = {- offset: number;-};--const backgroundMigrationId = "c19b91d9-f9a2-468b-8209-95578f970c5b";--export default class MigrateEventLogToBlobStorageRefTable 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 ClickHouse traces table exists- const tables = await clickhouseClient().query({- query: "SHOW TABLES",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route: "background-migration.migrateEventLogToBlobStorageRefTable",- }),- },- });- const tableNames = (await tables.json()).data as { name: string }[];- if (- !tableNames.some((r) => r.name === "event_log") ||- !tableNames.some((r) => r.name === "blob_storage_file_log")- ) {- // Retry if the table does not exist as this may mean migrations are still pending- if (attempts > 0) {- logger.info(- `ClickHouse event_log or blob_storage_file_log tables do not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);- });- }-- // If all retries are exhausted, return as invalid- return {- valid: false,- invalidReason:- "ClickHouse event_log or blob_storage_file_log tables do not exist",- };- }-- return { valid: true, invalidReason: undefined };- }-- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- logger.info(- `Migrating from event_log table to blob_storage_file_log with ${JSON.stringify(args)}`,- );-- // @ts-ignore- const initialMigrationState: {- state: MigrationState;- } = await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const maxRowsToProcess = Number(args.maxRowsToProcess ?? Infinity);- const batchSize = Number(args.batchSize ?? 200_000);-- const initialState = initialMigrationState.state.offset- ? initialMigrationState.state- : {- offset: Number(args.offset ?? 0),- };-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: initialState },- });- let processedRows = 0;- while (- !this.isAborted &&- !this.isFinished &&- processedRows < maxRowsToProcess- ) {- const fetchStart = Date.now();-- // @ts-ignore- const migrationState: { state: MigrationState } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- // ordered by time ascending.- await insertIntoS3RefsTableFromEventLog(- batchSize,- migrationState.state.offset,- );-- logger.info(- `Inserted up to ${batchSize} records into blob_storage_file_log in ${Date.now() - fetchStart}ms`,- );-- const lastEventLogPrimaryKey = await getLastEventLogPrimaryKey();-- if (!lastEventLogPrimaryKey) {- logger.info("Event log table is empty. Exiting...");- break;- }-- const s3Refs = await findS3RefsByPrimaryKey(lastEventLogPrimaryKey);-- if (s3Refs.length > 0) {- logger.info("No more event logs to migrate. Exiting...");- this.isFinished = true;- }-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: {- state: {- offset: migrationState.state.offset + batchSize,- },- },- });- }-- if (this.isAborted) {- logger.info(- `Migration of event_log table to blob storage log aborted after processing ${processedRows} rows. Skipping cleanup.`,- );- return;- }-- logger.info(- `Finished migration of event_log table to blob storage log in ${Date.now() - start}ms`,- );- }-- async abort(): Promise<void> {- logger.info(`Aborting migration of event_log table to blob storage log`);- this.isAborted = true;- }-}--async function main() {- const args = parseArgs({- options: {- batchSize: { type: "string", short: "b", default: "1000" },- maxRowsToProcess: { type: "string", short: "r", default: "Infinity" },- maxDate: {- type: "string",- short: "d",- default: new Date("1970-01-01T00:00:00.000Z").toISOString(),- },- },- });-- const migration = new MigrateEventLogToBlobStorageRefTable();- await migration.validate(args.values);- await migration.run(args.values);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`, error);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/migrateObservationsFromPostgresToClickhouse.ts b/worker/src/backgroundMigrations/migrateObservationsFromPostgresToClickhouse.tsdeleted file mode 100644index 236fb3b238..0000000000--- a/worker/src/backgroundMigrations/migrateObservationsFromPostgresToClickhouse.ts+++ /dev/null@@ -1,234 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- buildClickHouseLogComment,- clickhouseClient,- convertPostgresObservationToInsert,- logger,-} from "@langfuse/shared/src/server";-import { parseArgs } from "node:util";-import { prisma, Prisma } from "@langfuse/shared/src/db";-import { env } from "../env";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table-const backgroundMigrationId = "7526e7c9-0026-4595-af2c-369dfd9176ec";--export default class MigrateObservationsFromPostgresToClickhouse implements IBackgroundMigration {- private isAborted = false;- private isFinished = false;-- private async updateMaxDate(stateSuffix: string, maxDate: Date) {- await prisma.$transaction(- async (tx) => {- // @ts-ignore- const migrationState: { state: Record<string, string> } =- await tx.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });- migrationState.state[`maxDate${stateSuffix}`] = maxDate.toISOString();- await tx.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: migrationState.state },- });- },- {- maxWait: 5000,- isolationLevel: Prisma.TransactionIsolationLevel.Serializable,- },- );- }-- private async getMaxDate(stateSuffix: string): Promise<Date | undefined> {- // @ts-ignore- const migrationState: { state: Record<string, string | undefined> } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- return migrationState.state?.[`maxDate${stateSuffix}`]- ? new Date(migrationState.state[`maxDate${stateSuffix}`] as string)- : undefined;- }-- 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 ClickHouse observations table exists- const tables = await clickhouseClient().query({- query: "SHOW TABLES",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route:- "background-migration.migrateObservationsFromPostgresToClickhouse",- }),- },- });- const tableNames = (await tables.json()).data as { name: string }[];- if (!tableNames.some((r) => r.name === "observations")) {- // Retry if the table does not exist as this may mean migrations are still pending- if (attempts > 0) {- logger.info(- `ClickHouse observations table does not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);- });- }-- // If all retries are exhausted, return as invalid- return {- valid: false,- invalidReason: "ClickHouse observations table does not exist",- };- }-- return { valid: true, invalidReason: undefined };- }-- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- logger.info(- `Migrating observations from postgres to clickhouse with ${JSON.stringify(args)}`,- );-- const stateSuffix = (args.stateSuffix as string) ?? "";- const initialDate = await this.getMaxDate(stateSuffix);- const maxRowsToProcess = Number(args.maxRowsToProcess ?? Infinity);- const batchSize = Number(args.batchSize ?? 1000);- const maxDate =- initialDate ?? new Date((args.maxDate as string) ?? new Date());-- await this.updateMaxDate(stateSuffix, maxDate);-- let processedRows = 0;- while (- !this.isAborted &&- !this.isFinished &&- processedRows < maxRowsToProcess- ) {- const fetchStart = Date.now();-- const maxDate = await this.getMaxDate(stateSuffix);- logger.info(`Max date: ${maxDate?.toISOString()}`);-- const observations = await prisma.$queryRaw<- Array<Record<string, any>>- >(Prisma.sql`- SELECT o.id, o.trace_id, o.project_id, o.type, o.parent_observation_id, o.start_time, o.end_time, o.name, o.metadata, o.level, o.status_message, o.version, o.input, o.output, o.unit, o.model, o.internal_model_id, o."modelParameters" as model_parameters, o.prompt_tokens, o.completion_tokens, o.total_tokens, o.completion_start_time, o.prompt_id, p.name as prompt_name, p.version as prompt_version, o.input_cost, o.output_cost, o.total_cost, o.calculated_input_cost, o.calculated_output_cost, o.calculated_total_cost, o.created_at, o.updated_at- FROM observations o- LEFT JOIN prompts p ON o.prompt_id = p.id- WHERE o.created_at <= ${maxDate}- ORDER BY o.created_at DESC- LIMIT ${batchSize};- `);- if (observations.length === 0) {- logger.info("No more observations to migrate. Exiting...");- break;- }-- logger.info(- `Got ${observations.length} records from Postgres in ${Date.now() - fetchStart}ms`,- );-- const insertStart = Date.now();- await clickhouseClient().insert({- table: "observations",- values: observations.map(convertPostgresObservationToInsert),- format: "JSONEachRow",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route:- "background-migration.migrateObservationsFromPostgresToClickhouse",- }),- },- });-- logger.info(- `Inserted ${observations.length} observations into Clickhouse in ${Date.now() - insertStart}ms`,- );-- await this.updateMaxDate(- stateSuffix,- new Date(observations[observations.length - 1].created_at),- );-- if (observations.length < batchSize) {- logger.info("No more observations to migrate. Exiting...");- this.isFinished = true;- }-- processedRows += observations.length;- logger.info(- `Processed batch in ${Date.now() - fetchStart}ms. Oldest record in batch: ${new Date(observations[observations.length - 1].created_at).toISOString()}`,- );- }-- if (this.isAborted) {- logger.info(- `Migration of observations from Postgres to Clickhouse aborted after processing ${processedRows} rows. Skipping cleanup.`,- );- return;- }-- logger.info(- `Finished migration of observations from Postgres to Clickhouse in ${Date.now() - start}ms`,- );- }-- async abort(): Promise<void> {- logger.info(- `Aborting migration of observations from Postgres to clickhouse`,- );- this.isAborted = true;- }-}--async function main() {- const args = parseArgs({- options: {- batchSize: { type: "string", short: "b", default: "1000" },- maxRowsToProcess: { type: "string", short: "r", default: "Infinity" },- maxDate: {- type: "string",- short: "d",- default: new Date().toISOString(),- },- // State prefix can be used to start multiple migrations at once.- // We add it to the end of the `maxDate` state key which makes the runs unique and restartable.- stateSuffix: { type: "string", short: "s", default: "" },- },- });-- const migration = new MigrateObservationsFromPostgresToClickhouse();- await migration.validate(args.values);- await migration.run(args.values);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/migrateScoresFromPostgresToClickhouse.ts b/worker/src/backgroundMigrations/migrateScoresFromPostgresToClickhouse.tsdeleted file mode 100644index 2b60bfaab4..0000000000--- a/worker/src/backgroundMigrations/migrateScoresFromPostgresToClickhouse.ts+++ /dev/null@@ -1,208 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- buildClickHouseLogComment,- clickhouseClient,- convertPostgresScoreToInsert,- logger,-} from "@langfuse/shared/src/server";-import { parseArgs } from "node:util";-import { prisma, Prisma } from "@langfuse/shared/src/db";-import { env } from "../env";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table-const backgroundMigrationId = "94e50334-50d3-4e49-ad2e-9f6d92c85ef7";--export default class MigrateScoresFromPostgresToClickhouse 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 ClickHouse scores table exists- const tables = await clickhouseClient().query({- query: "SHOW TABLES",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route: "background-migration.migrateScoresFromPostgresToClickhouse",- }),- },- });- const tableNames = (await tables.json()).data as { name: string }[];- if (!tableNames.some((r) => r.name === "scores")) {- // Retry if the table does not exist as this may mean migrations are still pending- if (attempts > 0) {- logger.info(- `ClickHouse scores table does not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);- });- }-- // If all retries are exhausted, return as invalid- return {- valid: false,- invalidReason: "ClickHouse scores table does not exist",- };- }-- return { valid: true, invalidReason: undefined };- }-- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- logger.info(- `Migrating scores from postgres to clickhouse with ${JSON.stringify(args)}`,- );-- // @ts-ignore- const initialMigrationState: { state: { maxDate: string | undefined } } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const maxRowsToProcess = Number(args.maxRowsToProcess ?? Infinity);- const batchSize = Number(args.batchSize ?? 1000);- const maxDate = initialMigrationState.state?.maxDate- ? new Date(initialMigrationState.state.maxDate)- : new Date((args.maxDate as string) ?? new Date());-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: { maxDate } },- });-- let processedRows = 0;- while (- !this.isAborted &&- !this.isFinished &&- processedRows < maxRowsToProcess- ) {- const fetchStart = Date.now();-- // @ts-ignore- const migrationState: { state: { maxDate: string } } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const scores = await prisma.$queryRaw<- Array<Record<string, any>>- >(Prisma.sql`- SELECT id, timestamp, project_id, trace_id, observation_id, name, value, source, comment, author_user_id, config_id, data_type, string_value, queue_id, created_at, updated_at- FROM scores- WHERE created_at <= ${new Date(migrationState.state.maxDate)}- ORDER BY created_at DESC- LIMIT ${batchSize};- `);- if (scores.length === 0) {- logger.info("No more scores to migrate. Exiting...");- break;- }-- logger.info(- `Got ${scores.length} records from Postgres in ${Date.now() - fetchStart}ms`,- );-- const insertStart = Date.now();- await clickhouseClient().insert({- table: "scores",- values: scores.map(convertPostgresScoreToInsert),- format: "JSONEachRow",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route: "background-migration.migrateScoresFromPostgresToClickhouse",- }),- },- });-- logger.info(- `Inserted ${scores.length} scores into Clickhouse in ${Date.now() - insertStart}ms`,- );-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: {- state: {- maxDate: new Date(scores[scores.length - 1].created_at),- },- },- });-- if (scores.length < batchSize) {- logger.info("No more scores to migrate. Exiting...");- this.isFinished = true;- }-- processedRows += scores.length;- logger.info(- `Processed batch in ${Date.now() - fetchStart}ms. Oldest record in batch: ${new Date(scores[scores.length - 1].created_at).toISOString()}`,- );- }-- if (this.isAborted) {- logger.info(- `Migration of scores from Postgres to Clickhouse aborted after processing ${processedRows} rows. Skipping cleanup.`,- );- return;- }-- logger.info(- `Finished migration of scores from Postgres to Clickhouse in ${Date.now() - start}ms`,- );- }-- async abort(): Promise<void> {- logger.info(`Aborting migration of scores from Postgres to clickhouse`);- this.isAborted = true;- }-}--async function main() {- const args = parseArgs({- options: {- batchSize: { type: "string", short: "b", default: "1000" },- maxRowsToProcess: { type: "string", short: "r", default: "Infinity" },- maxDate: {- type: "string",- short: "d",- default: new Date().toISOString(),- },- },- });-- const migration = new MigrateScoresFromPostgresToClickhouse();- await migration.validate(args.values);- await migration.run(args.values);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/backgroundMigrations/migrateTracesFromPostgresToClickhouse.ts b/worker/src/backgroundMigrations/migrateTracesFromPostgresToClickhouse.tsdeleted file mode 100644index 8b483d2bc1..0000000000--- a/worker/src/backgroundMigrations/migrateTracesFromPostgresToClickhouse.ts+++ /dev/null@@ -1,208 +0,0 @@-import { IBackgroundMigration } from "./IBackgroundMigration";-import {- buildClickHouseLogComment,- clickhouseClient,- convertPostgresTraceToInsert,- logger,-} from "@langfuse/shared/src/server";-import { parseArgs } from "node:util";-import { prisma, Prisma } from "@langfuse/shared/src/db";-import { env } from "../env";--// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table-const backgroundMigrationId = "5960f22a-748f-480c-b2f3-bc4f9d5d84bc";--export default class MigrateTracesFromPostgresToClickhouse 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 ClickHouse traces table exists- const tables = await clickhouseClient().query({- query: "SHOW TABLES",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route: "background-migration.migrateTracesFromPostgresToClickhouse",- }),- },- });- const tableNames = (await tables.json()).data as { name: string }[];- if (!tableNames.some((r) => r.name === "traces")) {- // Retry if the table does not exist as this may mean migrations are still pending- if (attempts > 0) {- logger.info(- `ClickHouse traces table does not exist. Retrying in 10s...`,- );- return new Promise((resolve) => {- setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);- });- }-- // If all retries are exhausted, return as invalid- return {- valid: false,- invalidReason: "ClickHouse traces table does not exist",- };- }-- return { valid: true, invalidReason: undefined };- }-- async run(args: Record<string, unknown>): Promise<void> {- const start = Date.now();- logger.info(- `Migrating traces from postgres to clickhouse with ${JSON.stringify(args)}`,- );-- // @ts-ignore- const initialMigrationState: { state: { maxDate: string | undefined } } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const maxRowsToProcess = Number(args.maxRowsToProcess ?? Infinity);- const batchSize = Number(args.batchSize ?? 1000);- const maxDate = initialMigrationState.state?.maxDate- ? new Date(initialMigrationState.state.maxDate)- : new Date((args.maxDate as string) ?? new Date());-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: { state: { maxDate } },- });-- let processedRows = 0;- while (- !this.isAborted &&- !this.isFinished &&- processedRows < maxRowsToProcess- ) {- const fetchStart = Date.now();-- // @ts-ignore- const migrationState: { state: { maxDate: string } } =- await prisma.backgroundMigration.findUniqueOrThrow({- where: { id: backgroundMigrationId },- select: { state: true },- });-- const traces = await prisma.$queryRaw<- Array<Record<string, any>>- >(Prisma.sql`- SELECT id, timestamp, name, user_id, metadata, release, version, project_id, public, bookmarked, tags, input, output, session_id, created_at, updated_at- FROM traces- WHERE created_at <= ${new Date(migrationState.state.maxDate)}- ORDER BY created_at DESC- LIMIT ${batchSize};- `);- if (traces.length === 0) {- logger.info("No more traces to migrate. Exiting...");- break;- }-- logger.info(- `Got ${traces.length} records from Postgres in ${Date.now() - fetchStart}ms`,- );-- const insertStart = Date.now();- await clickhouseClient().insert({- table: "traces",- values: traces.map(convertPostgresTraceToInsert),- format: "JSONEachRow",- clickhouse_settings: {- log_comment: buildClickHouseLogComment({- surface: "worker",- route: "background-migration.migrateTracesFromPostgresToClickhouse",- }),- },- });-- logger.info(- `Inserted ${traces.length} traces into Clickhouse in ${Date.now() - insertStart}ms`,- );-- await prisma.backgroundMigration.update({- where: { id: backgroundMigrationId },- data: {- state: {- maxDate: new Date(traces[traces.length - 1].created_at),- },- },- });-- if (traces.length < batchSize) {- logger.info("No more traces to migrate. Exiting...");- this.isFinished = true;- }-- processedRows += traces.length;- logger.info(- `Processed batch in ${Date.now() - fetchStart}ms. Oldest record in batch: ${new Date(traces[traces.length - 1].created_at).toISOString()}`,- );- }-- if (this.isAborted) {- logger.info(- `Migration of traces from Postgres to Clickhouse aborted after processing ${processedRows} rows. Skipping cleanup.`,- );- return;- }-- logger.info(- `Finished migration of traces from Postgres to Clickhouse in ${Date.now() - start}ms`,- );- }-- async abort(): Promise<void> {- logger.info(`Aborting migration of traces from Postgres to clickhouse`);- this.isAborted = true;- }-}--async function main() {- const args = parseArgs({- options: {- batchSize: { type: "string", short: "b", default: "1000" },- maxRowsToProcess: { type: "string", short: "r", default: "Infinity" },- maxDate: {- type: "string",- short: "d",- default: new Date().toISOString(),- },- },- });-- const migration = new MigrateTracesFromPostgresToClickhouse();- await migration.validate(args.values);- await migration.run(args.values);-}--// If the script is being executed directly (not imported), run the main function-if (require.main === module) {- main()- .then(() => {- process.exit(0);- })- .catch((error) => {- logger.error(`Migration execution failed: ${error}`, error);- process.exit(1); // Exit with an error code- });-}diff --git a/worker/src/scripts/verifyClickhouseRecords/README.md b/worker/src/scripts/verifyClickhouseRecords/README.mddeleted file mode 100644index 3b08b732a2..0000000000--- a/worker/src/scripts/verifyClickhouseRecords/README.md+++ /dev/null@@ -1,36 +0,0 @@-# Verify Clickhouse Records--This script is used to compare Clickhouse records to our Postgres records.-Per default, it draws a sample of observations, traces, and scores from the Postgres-tables and executes single queries on Clickhouse to compare the individual fields.-It is possible to overwrite the selection process using the overwriteIds per type.--## Usage--To compare the records configure the database environment variables and afterward-execute the script.-Modify the `DATE_START` setting in the script to a date after the clickhouse sync was in place.-Set `ITERATIONS` based on the number of records that you want to validate. We sample 100 records per kind-in each iteration.--```bash-# Insert postgres database URL-export DATABASE_URL=-export CLICKHOUSE_URL=-export CLICKHOUSE_USER=-export CLICKHOUSE_PASSWORD=--cd worker/src/scripts/verifyClickhouseRecords--npx tsx index.ts-```--The script writes the objects and deltas into the `output` folder within the current working directory.-Use it to validate whether Clickhouse and Postgres produce equal results.--## Known Issues--### Numeric values--Postgres seems to retain a higher precision for floating point numeric numbers.-In the object comparisons this frequently leads to false positives in the 10^-8 range.diff --git a/worker/src/scripts/verifyClickhouseRecords/index.ts b/worker/src/scripts/verifyClickhouseRecords/index.tsdeleted file mode 100644index 4e91abd55f..0000000000--- a/worker/src/scripts/verifyClickhouseRecords/index.ts+++ /dev/null@@ -1,967 +0,0 @@-import { writeFile } from "node:fs/promises";-import path from "node:path";-import { parseJsonPrioritised } from "@langfuse/shared";-import { prisma, Prisma } from "@langfuse/shared/src/db";-import {- clickhouseClient,- clickhouseStringDateSchema,- logger,-} from "@langfuse/shared/src/server";--const getErrorMessage = (params: {- type: "observation" | "trace" | "score";- projectId: string;- id: string;- key: string;- pgValue: any;- chValue: any;-}) => {- const delta = `[${params.projectId}-${params.type}-${params.id}] Mismatch between Postgres and Clickhouse:\n${JSON.stringify(params, null, 2)}`;- return delta;-};--// Constants-const LIMIT = 100;-const ITERATIONS = 10;-const DATE_START = new Date("2024-11-02T00:00:00.000Z");-const DATE_END = new Date(Date.now() - 1000 * 60 * 15); // 15 minutes ago--const TABLE_SAMPLE_RATE = 0.05;--// Execution-main({- overwriteObservationIds: [],- overwriteTraceIds: [],- overwriteScoreIds: [],-}).then(() => {- logger.info("done");- process.exit(0);-});--type MainParams = {- overwriteObservationIds: string[];- overwriteTraceIds: string[];- overwriteScoreIds: string[];-};--async function main(params: MainParams) {- const { overwriteObservationIds, overwriteTraceIds, overwriteScoreIds } =- params;-- const hasOverwrite = [- overwriteObservationIds,- overwriteTraceIds,- overwriteScoreIds,- ].some((o) => o.length > 0);-- const failedObservationList: string[] = [];- const failedTraceList: string[] = [];- const failedScoreList: string[] = [];- const checkedObservationSet = new Set<string>();- const checkedTraceSet = new Set<string>();- const checkedScoreSet = new Set<string>();-- let totalObservationCount = 0;- let totalTraceCount = 0;- let totalScoreCount = 0;- let currentIteration = 0;-- while (currentIteration < ITERATIONS) {- logger.info(`Iteration ${currentIteration + 1}/${ITERATIONS}`);-- // Check observations- let observations: unknown[] = [];-- if (overwriteObservationIds.length > 0) {- observations = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT- *- FROM- observations- WHERE- id IN (${Prisma.join(overwriteObservationIds, ", ")})- `,- );- } else if (!hasOverwrite) {- const randomObservations = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT- *- FROM- observations TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})- WHERE- start_time > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'- AND start_time < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'- LIMIT ${LIMIT}- `,- );-- observations = randomObservations;- }-- logger.info(`Verifying ${observations.length} observations...`);-- try {- const results = await Promise.allSettled(- observations.map(async (obs) => {- const id = (obs as any).id;- if (checkedObservationSet.has(id)) {- return;- }- totalObservationCount += 1;- checkedObservationSet.add(id);-- await verifyClickhouseObservation(obs);- }),- );-- results.forEach((result, i) => {- if (result.status === "rejected") {- const message = `[${i}] ` + result.reason;- failedObservationList.push(message);-- logger.error(message);- }- });- } catch (e) {- logger.error(e);- }-- // Check traces- let traces: unknown[] = [];- if (overwriteTraceIds.length > 0) {- traces = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT *- FROM traces- WHERE- id IN (${Prisma.join(overwriteTraceIds, ", ")})- `,- );- } else if (!hasOverwrite) {- const randomTraces = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT *- FROM traces TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})- WHERE- timestamp > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'- AND timestamp < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'- LIMIT ${LIMIT}- `,- );-- traces = randomTraces;- }-- logger.info(`Verifying ${traces.length} traces...`);-- try {- const results = await Promise.allSettled(- traces.map(async (trace) => {- const id = (trace as any).id;- if (checkedTraceSet.has(id)) {- return;- }- totalTraceCount += 1;- checkedTraceSet.add(id);-- await verifyClickhouseTrace(trace);- }),- );-- results.forEach((result, i) => {- if (result.status === "rejected") {- const message = `[${i}] ` + result.reason;- failedTraceList.push(message);-- logger.error(message);- }- });- } catch (e) {- logger.error(e);- }-- // Check scores- let scores: unknown[] = [];- if (overwriteScoreIds.length > 0) {- scores = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT *- FROM scores- WHERE- id IN (${Prisma.join(overwriteScoreIds, ", ")})- `,- );- } else if (!hasOverwrite) {- const randomScores = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT *- FROM scores TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})- WHERE- timestamp > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'- AND timestamp < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'- AND source = 'API'- LIMIT ${LIMIT}- `,- );-- scores = randomScores;- }-- logger.info(`Verifying ${scores.length} scores...`);-- try {- const results = await Promise.allSettled(- scores.map(async (score) => {- const id = (score as any).id;- if (checkedScoreSet.has(id)) {- return;- }- totalScoreCount += 1;-- checkedScoreSet.add(id);-- await verifyClickhouseScore(score);- }),- );-- results.forEach((result, i) => {- if (result.status === "rejected") {- const message = `[${i}] ` + result.reason;- failedScoreList.push(message);-- logger.error(message);- }- });- } catch (e) {- logger.error(e);- }-- currentIteration++;- if (hasOverwrite) break;- }-- logger.info(`Total observations verified: ${totalObservationCount}`);- logger.info(`Total traces verified: ${totalTraceCount}`);- logger.info(`Total scores verified: ${totalScoreCount}`);-- if (failedObservationList.length > 0) {- const outPath = path.join(- process.cwd(),- `/output/${new Date().toISOString()}_failedObservations.txt`,- );- await writeFile(outPath, failedObservationList.join("\n"));- logger.error(- `Failed to verify ${failedObservationList.length} out of ${totalObservationCount} observations`,- );- } else {- logger.info(- `All ${totalObservationCount} observations verified successfully`,- );- }-- if (failedTraceList.length > 0) {- const outPath = path.join(- process.cwd(),- `/output/${new Date().toISOString()}_failedTraces.txt`,- );- await writeFile(outPath, failedTraceList.join("\n"));- logger.error(- `Failed to verify ${failedTraceList.length} out of ${totalTraceCount} traces`,- );- } else {- logger.info(`All ${totalTraceCount} traces verified successfully`);- }-- if (failedScoreList.length > 0) {- const outPath = path.join(- process.cwd(),- `/output/${new Date().toISOString()}_failedScores.txt`,- );- await writeFile(outPath, failedScoreList.join("\n"));- logger.error(- `Failed to verify ${failedScoreList.length} out of ${totalScoreCount} scores`,- );- } else {- logger.info(`All ${totalScoreCount} scores verified successfully`);- }-}--async function verifyClickhouseObservation(postgresObservation: any) {- const { id: observationId, project_id: projectId } = postgresObservation;- const clickhouseResult = await clickhouseClient().query({- query: `SELECT * FROM observations WHERE project_id = '${projectId}' AND id = '${observationId}' ORDER BY updated_at DESC LIMIT 1`,- format: "JSONEachRow",- });-- const clickhouseRecord = (await clickhouseResult.json()).shift();- if (!clickhouseRecord) {- throw new Error(- `Observation ${observationId} not found in Clickhouse for project ${projectId}`,- );- }-- logger.info(`Comparing delta for observation ${projectId}-${observationId}`);-- for (const key in postgresObservation) {- const pgValue = postgresObservation[key];- const chValue = (clickhouseRecord as any)[key];-- switch (key) {- // Different by nature- case "created_at":- case "updated_at":- continue;-- // Dropped in CH- case "internal_model":- continue;-- // Same in PG as in CH- case "id":- case "name":- case "parent_observation_id":- case "type":- case "trace_id":- case "project_id":- case "prompt_id":- case "level":- case "status_message":- case "version":- case "internal_model_id": {- if (pgValue && pgValue !== chValue) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue,- }),- );- }-- break;- }-- case "unit":- break;-- // Start_time cannot be overwritten in CH, so they are allowed to be different- case "start_time": {- if (- pgValue &&- chValue &&- typeof pgValue.toISOString() !==- typeof clickhouseStringDateSchema.parse(chValue)- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue,- }),- );- }-- break;- }-- // Dates- case "completion_start_time":- case "end_time": {- if (- pgValue &&- chValue &&- pgValue.toISOString() !== clickhouseStringDateSchema.parse(chValue)- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue,- }),- );- }-- break;- }-- case "metadata": {- if (!pgValue && JSON.stringify(chValue) === "{}") continue;-- const parsedChMetadata =- "metadata" in chValue && Object.keys(chValue).length === 1- ? parseJsonPrioritised(chValue.metadata)- : Object.fromEntries(- Object.entries(chValue).map(([k, v]) => [k, v]),- );-- if (- JSON.stringify(pgValue, Object.keys(pgValue).sort()) !==- JSON.stringify(- parsedChMetadata,- typeof parsedChMetadata === "string"- ? undefined- : Object.keys(parsedChMetadata as any).sort(),- )- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: parsedChMetadata,- }),- );- }-- break;- }-- case "model":- if (pgValue !== (clickhouseRecord as any)["provided_model_name"]) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue,- }),- );- }-- break;-- case "input":- case "output": {- const parsedPgValue = parseJsonPrioritised(pgValue);- const parsedChValue = parseJsonPrioritised(chValue);-- if (- parsedPgValue &&- JSON.stringify(parsedPgValue, Object.keys(parsedPgValue).sort()) !==- JSON.stringify(- parsedChValue,- Object.keys(parsedChValue as any).sort(),- )- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue: JSON.stringify(parsedPgValue),- chValue: JSON.stringify(parsedChValue),- }),- );- }-- break;- }-- case "modelParameters": {- const parsedPgValue = pgValue;- const parsedChValue = JSON.parse(- (clickhouseRecord as any)["model_parameters"],- );-- if (- parsedPgValue &&- JSON.stringify(parsedPgValue, Object.keys(parsedPgValue).sort()) !==- JSON.stringify(parsedChValue, Object.keys(parsedChValue).sort())- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: parsedChValue,- }),- );- }-- break;- }-- case "completion_tokens": {- if (- pgValue !== 0 &&- pgValue.toString() !==- (clickhouseRecord as any)["usage_details"]["output"]- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["usage_details"]["output"],- }),- );- }-- break;- }-- case "prompt_tokens": {- if (- pgValue !== 0 &&- pgValue.toString() !==- (clickhouseRecord as any)["usage_details"]["input"]- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["usage_details"]["input"],- }),- );- }-- break;- }-- case "total_tokens": {- if (- pgValue !== 0 &&- pgValue.toString() !==- (clickhouseRecord as any)["usage_details"]["total"]- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["usage_details"]["total"],- }),- );- }-- break;- }-- case "calculated_input_cost": {- if (- pgValue !== null &&- Math.abs(- Number(pgValue) -- (clickhouseRecord as any)["cost_details"]["input"],- ) > 1e-9- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["cost_details"]["input"],- }),- );- }-- break;- }-- case "calculated_output_cost": {- if (- pgValue !== null &&- Math.abs(- Number(pgValue) -- (clickhouseRecord as any)["cost_details"]["output"],- ) > 1e-9- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["cost_details"]["output"],- }),- );- }-- break;- }-- case "calculated_total_cost": {- if (- pgValue !== null &&- Math.abs(- Number(pgValue) -- (clickhouseRecord as any)["cost_details"]["total"],- ) > 1e-9- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["cost_details"]["total"],- }),- );- }-- break;- }-- case "input_cost": {- if (- pgValue !== null &&- Math.abs(- Number(pgValue) -- (clickhouseRecord as any)["provided_cost_details"]["input"],- ) > 1e-9- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["provided_cost_details"][- "input"- ],- }),- );- }-- break;- }-- case "output_cost": {- if (- pgValue !== null &&- Math.abs(- Number(pgValue) -- (clickhouseRecord as any)["provided_cost_details"]["output"],- ) > 1e-9- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue,- chValue: (clickhouseRecord as any)["provided_cost_details"][- "output"- ],- }),- );- }-- break;- }-- case "total_cost": {- if (- pgValue !== null &&- Math.abs(- Number(pgValue) -- (clickhouseRecord as any)["provided_cost_details"]["total"],- ) > 1e-9- ) {- throw new Error(- getErrorMessage({- projectId,- id: observationId,- type: "observation",- key,- pgValue: Number(pgValue),- chValue: (clickhouseRecord as any)["provided_cost_details"][- "total"- ],- }),- );- }-- break;- }-- default:- throw Error("Unhandled observation key: " + key);- }- }-}--async function verifyClickhouseTrace(postgresTrace: any) {- const { id: traceId, project_id: projectId } = postgresTrace;-- const clickhouseResult = await clickhouseClient().query({- query: `SELECT * FROM traces WHERE project_id = '${projectId}' AND id = '${traceId}' ORDER BY updated_at DESC LIMIT 1`,- format: "JSONEachRow",- });-- const clickhouseTrace = (await clickhouseResult.json())[0];- if (!clickhouseTrace) {- throw new Error(- `Trace ${traceId} not found in Clickhouse for project ${projectId}`,- );- }-- for (const key of Object.keys(postgresTrace)) {- const pgValue = postgresTrace[key];- const chValue = (clickhouseTrace as any)[key];-- switch (key) {- // Different by nature- case "created_at":- case "updated_at":- continue;-- // Dropped in CH- case "external_id":- continue;-- // Same in PG as in CH- case "id":- case "name":- case "project_id":- case "user_id":- case "release":- case "public":- case "bookmarked":- case "session_id":- case "version": {- if (pgValue && pgValue !== chValue) {- throw new Error(- getErrorMessage({- projectId,- id: traceId,- type: "trace",- key,- pgValue,- chValue,- }),- );- }-- break;- }-- // timestamp cannot be overwritten in CH, so they are allowed to be different- case "timestamp": {- if (- pgValue &&- chValue &&- typeof pgValue.toISOString() !==- typeof clickhouseStringDateSchema.parse(chValue)- ) {- throw new Error(- getErrorMessage({- projectId,- id: traceId,- type: "trace",- key,- pgValue,- chValue,- }),- );- }-- break;- }-- case "metadata": {- if (!pgValue && JSON.stringify(chValue) === "{}") continue;-- const parsedChMetadata =- "metadata" in chValue && Object.keys(chValue).length === 1- ? parseJsonPrioritised(chValue.metadata)- : Object.fromEntries(- Object.entries(chValue).map(([k, v]) => [k, v]),- );-- if (- JSON.stringify(pgValue, Object.keys(pgValue).sort()) !==- JSON.stringify(- parsedChMetadata,- typeof parsedChMetadata === "string"- ? undefined- : Object.keys(parsedChMetadata as any).sort(),- )- ) {- throw new Error(- getErrorMessage({- projectId,- id: traceId,- type: "trace",- key,- pgValue,- chValue: parsedChMetadata,- }),- );- }-- break;- }-- case "tags":- if (JSON.stringify(pgValue) !== JSON.stringify(chValue)) {- throw new Error(- getErrorMessage({- projectId,- id: traceId,- type: "trace",- key,- pgValue,- chValue,- }),- );- }-- break;-- case "input":- case "output": {- const parsedPgValue = parseJsonPrioritised(pgValue);- const parsedChValue = parseJsonPrioritised(chValue);-- if (- parsedPgValue &&- JSON.stringify(parsedPgValue, Object.keys(parsedPgValue).sort()) !==- JSON.stringify(- parsedChValue,- parsedChValue instanceof Object- ? Object.keys(parsedChValue as any).sort()- : undefined,- )- ) {- throw new Error(- getErrorMessage({- projectId,- id: traceId,- type: "trace",- key,- pgValue: JSON.stringify(parsedPgValue),- chValue: JSON.stringify(parsedChValue),- }),- );- }-- break;- }-- default:- throw Error("Unhandled trace key: " + key);- }- }-}--async function verifyClickhouseScore(postgresScore: any) {- const { id: scoreId, project_id: projectId } = postgresScore;-- const clickhouseResult = await clickhouseClient().query({- query: `SELECT * FROM scores WHERE project_id = '${projectId}' AND id = '${scoreId}' ORDER BY updated_at DESC LIMIT 1`,- format: "JSONEachRow",- });-- const clickhouseScore = (await clickhouseResult.json())[0];- if (!clickhouseScore) {- throw new Error(- `Score ${scoreId} not found in Clickhouse for project ${projectId}`,- );- }-- for (const key of Object.keys(postgresScore)) {- const pgValue = postgresScore[key];- const chValue = (clickhouseScore as any)[key];-- switch (key) {- // Different by nature- case "created_at":- case "updated_at":- continue;-- // Same in PG as in CH- case "id":- case "name":- case "queue_id":- case "project_id":- case "value":- case "observation_id":- case "trace_id":- case "comment":- case "source":- case "author_user_id":- case "config_id":- case "string_value":- case "data_type": {- // If types are numeric, we just check that they are very close to each other- if (- pgValue &&- ((typeof pgValue === "number" &&- Math.abs(pgValue - chValue) >= 0.00001) ||- pgValue !== chValue)- ) {- throw new Error(- getErrorMessage({- projectId,- id: scoreId,- type: "score",- key,- pgValue,- chValue,- }),- );- }-- break;- }-- // timestamp cannot be overwritten in CH, so they are allowed to be different- case "timestamp": {- if (- pgValue &&- chValue &&- typeof pgValue.toISOString() !==- typeof clickhouseStringDateSchema.parse(chValue)- ) {- throw new Error(- getErrorMessage({- projectId,- id: scoreId,- type: "score",- key,- pgValue,- chValue,- }),- );- }-- break;- }-- default:- throw Error("Unhandled score key: " + key);- }- }-}