🪢 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
chore: script backfill job for events table (#10038)
Steffen Schmitz91d1059cd5a3
diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex b2ff59cf18..8121d08ce2 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -178,9 +178,9 @@ CREATE TABLE IF NOT EXISTS events-- I/Oinput String CODEC(ZSTD(3)),- input_truncated String MATERIALIZED leftUTF8(input, 5000),+ input_truncated String MATERIALIZED leftUTF8(input, 1024),output String CODEC(ZSTD(3)),- output_truncated String MATERIALIZED leftUTF8(output, 5000),+ output_truncated String MATERIALIZED leftUTF8(output, 1024),-- TODO Metadata: Decide for approach-- -- Approach 1: Use plain JSON type with default configdiff --git a/worker/src/backgroundMigrations/backfillEventsHistoric.ts b/worker/src/backgroundMigrations/backfillEventsHistoric.tsnew file mode 100644index 0000000000..46c7895054--- /dev/null+++ b/worker/src/backgroundMigrations/backfillEventsHistoric.ts@@ -0,0 +1,679 @@+import { IBackgroundMigration } from "./IBackgroundMigration";+import {+ clickhouseClient,+ commandClickhouse,+ logger,+ queryClickhouse,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { env } from "../env";+import { parseArgs } from "node:util";++// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table+const backgroundMigrationId = "d8cf9f5e-747e-4ffe-8156-dec0eaebce9d";++interface PartitionState {+ modulo: number; // Power of 2 (1, 2, 4, 8, ..., maxModulo)+ rowCount: number; // Total rows in partition+ chunksProcessed: number[]; // Array of completed chunk IDs+ lastUpdated: string;+}++interface MigrationState {+ partitions: Record<string, PartitionState>;+ currentPartition: string | null;+ completedPartitions: string[];+}++interface MigrationArgs {+ targetChunkSize?: string; // Default: 20_000_000+ maxModulo?: string; // Default: 512+ batchTimeoutMs?: string; // Default: 7_200_000 (2h)+}++export default class BackfillEventsHistoric implements IBackgroundMigration {+ private isAborted = false;++ /**+ * Calculate the next power of 2 greater than or equal to n+ */+ private nextPowerOf2(n: number): number {+ if (n <= 1) return 1;+ return Math.pow(2, Math.ceil(Math.log2(n)));+ }++ /**+ * Calculate optimal modulo value based on row count and target chunk size.+ * Returns a power of 2 between 1 and maxModulo.+ */+ private calculateModulo(+ rowCount: number,+ targetChunkSize: number,+ maxModulo: number,+ ): number {+ if (rowCount === 0) return 1;++ const chunksNeeded = rowCount / targetChunkSize;+ const calculatedModulo = this.nextPowerOf2(Math.ceil(chunksNeeded));++ // Enforce minimum of 1 and maximum of maxModulo+ return Math.min(maxModulo, Math.max(1, calculatedModulo));+ }++ /**+ * Discover all partitions from observations table, ordered newest to oldest+ */+ private async discoverPartitions(): Promise<string[]> {+ logger.info("[Backfill Events] Discovering partitions from observations");++ const result = await queryClickhouse<{ partition: string }>({+ query: `+ SELECT DISTINCT _partition_id AS partition+ FROM observations+ WHERE is_deleted = 0+ ORDER BY partition DESC+ `,+ tags: {+ feature: "background-migration",+ operation: "discoverPartitions",+ },+ });++ const partitions = result.map((r) => r.partition);+ logger.info(+ `[Backfill Events] Discovered ${partitions.length} partitions: ${partitions.join(", ")}`,+ );++ return partitions;+ }++ /**+ * Count rows in a specific partition+ */+ private async countPartitionRows(partition: string): Promise<number> {+ logger.info(`[Backfill Events] Counting rows in partition ${partition}`);++ const result = await queryClickhouse<{ count: string }>({+ query: `+ SELECT count(*) AS count+ FROM observations+ WHERE _partition_id = '${partition}'+ AND is_deleted = 0+ `,+ tags: {+ feature: "background-migration",+ operation: "countPartitionRows",+ partition,+ },+ });++ const count = parseInt(result[0]?.count ?? "0", 10);+ logger.info(+ `[Backfill Events] Partition ${partition} has ${count.toLocaleString()} rows`,+ );++ return count;+ }++ /**+ * Load migration state from database+ */+ private async loadState(): Promise<MigrationState> {+ const migration = await prisma.backgroundMigration.findUnique({+ where: { id: backgroundMigrationId },+ select: { state: true },+ });++ const defaultState: MigrationState = {+ partitions: {},+ currentPartition: null,+ completedPartitions: [],+ };++ if (!migration || !migration.state) {+ return defaultState;+ }++ const state = migration.state as any;++ // Validate and merge with defaults to ensure all required fields exist+ return {+ partitions: state.partitions ?? defaultState.partitions,+ currentPartition: state.currentPartition ?? defaultState.currentPartition,+ completedPartitions:+ state.completedPartitions ?? defaultState.completedPartitions,+ };+ }++ /**+ * Update migration state in database+ */+ private async updateState(state: MigrationState): Promise<void> {+ await prisma.backgroundMigration.update({+ where: { id: backgroundMigrationId },+ data: { state: state as any },+ });+ }++ /**+ * Get the next chunk to process for a partition+ */+ private getNextChunkToProcess(partition: PartitionState): number | null {+ const { modulo, chunksProcessed } = partition;++ for (let i = 0; i < modulo; i++) {+ if (!chunksProcessed.includes(i)) {+ return i;+ }+ }++ return null; // All chunks processed+ }++ /**+ * Process a single chunk for the trace_attrs phase+ */+ private async processTraceAttrsChunk(+ partition: string,+ chunkId: number,+ modulo: number,+ timeoutMs: number,+ ): Promise<void> {+ logger.info(+ `[Backfill Events] Processing trace_attrs for chunk ${chunkId + 1}/${modulo} in partition ${partition}`,+ );++ await commandClickhouse({+ query: `+ INSERT INTO trace_attrs+ SELECT+ t.project_id,+ t.id AS trace_id,+ t.user_id,+ t.session_id,+ mapConcat(+ mapFilter((k,v) -> NOT in(k, ['attributes']), t.metadata),+ if(length(t.tags) > 0, map('trace_tags', toJSONString(t.tags)), map())+ ) AS metadata,+ t.event_ts,+ 0 AS is_deleted+ FROM traces t+ WHERE t._partition_id = '${partition}'+ AND (xxHash32(t.id) % ${modulo}) = ${chunkId}+ AND t.is_deleted = 0+ AND (t.user_id is not null OR t.session_id is not null OR length(mapKeys(t.metadata)) > 0 OR length(t.tags) > 0)+ `,+ tags: {+ feature: "background-migration",+ operation: "processTraceAttrsChunk",+ partition,+ chunkId: chunkId.toString(),+ },+ clickhouseConfigs: {+ request_timeout: timeoutMs,+ },+ clickhouseSettings: {+ http_headers_progress_interval_ms: "100000", // 100 seconds - prevent header overflow on long queries+ // max_insert_threads: "4",+ parallel_distributed_insert_select: "2",+ enable_parallel_replicas: 1,+ // max_threads: 4,+ min_insert_block_size_rows: "10048576",+ },+ });++ logger.info(+ `[Backfill Events] Completed trace_attrs for chunk ${chunkId + 1}/${modulo} in partition ${partition}`,+ );+ }++ /**+ * Process a single chunk for the events phase+ */+ private async processEventsChunk(+ partition: string,+ chunkId: number,+ modulo: number,+ timeoutMs: number,+ ): Promise<void> {+ logger.info(+ `[Backfill Events] Processing events for chunk ${chunkId + 1}/${modulo} in partition ${partition}`,+ );++ await commandClickhouse({+ query: `+ INSERT INTO events (+ project_id,+ trace_id,+ span_id,+ parent_span_id,+ start_time,+ end_time,+ name,+ type,+ environment,+ version,+ user_id,+ session_id,+ level,+ status_message,+ completion_start_time,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ total_cost,+ input,+ output,+ -- metadata,+ metadata_names,+ metadata_values,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_raw,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted+ )+ SELECT+ o.project_id,+ o.trace_id,+ o.id AS span_id,+ CASE+ WHEN o.id = concat('t-', o.trace_id) THEN ''+ ELSE coalesce(o.parent_observation_id, concat('t-', o.trace_id))+ END AS parent_span_id,+ greatest(o.start_time, toDateTime64('1970-01-01', 3)) AS start_time,+ o.end_time,+ o.name,+ o.type,+ o.environment,+ coalesce(o.version, '') AS version,+ coalesce(t.user_id, '') AS user_id,+ coalesce(t.session_id, '') AS session_id,+ o.level,+ coalesce(o.status_message, '') AS status_message,+ o.completion_start_time,+ o.prompt_id,+ o.prompt_name,+ CAST(o.prompt_version, 'Nullable(String)') AS prompt_version,+ o.internal_model_id AS model_id,+ o.provided_model_name,+ o.model_parameters,+ o.provided_usage_details,+ o.usage_details,+ o.provided_cost_details,+ o.cost_details,+ coalesce(o.total_cost, 0) AS total_cost,+ coalesce(o.input, '') AS input,+ coalesce(o.output, '') AS output,+ -- CAST(mapConcat(o.metadata, coalesce(t.metadata, map())), 'JSON') AS metadata,+ mapKeys(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_names,+ mapValues(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_values,+ multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,+ NULL AS service_name,+ NULL AS service_version,+ NULL AS scope_name,+ NULL AS scope_version,+ NULL AS telemetry_sdk_language,+ NULL AS telemetry_sdk_name,+ NULL AS telemetry_sdk_version,+ '' AS blob_storage_file_path,+ '' AS event_raw,+ byteSize(*) AS event_bytes,+ o.created_at,+ o.updated_at,+ o.event_ts,+ o.is_deleted+ FROM observations o+ LEFT ANY JOIN trace_attrs t+ ON o.project_id = t.project_id+ AND o.trace_id = t.trace_id+ WHERE o._partition_id = '${partition}'+ AND (xxHash32(o.trace_id) % ${modulo}) = ${chunkId}+ AND o.is_deleted = 0+ `,+ tags: {+ feature: "background-migration",+ operation: "processEventsChunk",+ partition,+ chunkId: chunkId.toString(),+ },+ clickhouseConfigs: {+ request_timeout: timeoutMs,+ },+ clickhouseSettings: {+ http_headers_progress_interval_ms: "100000", // 100 seconds - prevent header overflow on long queries+ min_insert_block_size_rows: "10048576",+ // join_algorithm: "partial_merge",+ min_insert_block_size_bytes: "512Mi",+ parallel_distributed_insert_select: "2",+ enable_parallel_replicas: "1",+ type_json_skip_duplicated_paths: 1,+ // TODO: May need fine-tuning for self-hosters+ allow_experimental_parallel_reading_from_replicas: "1",+ max_parallel_replicas: "2",+ },+ });++ logger.info(+ `[Backfill Events] Completed events for chunk ${chunkId + 1}/${modulo} in partition ${partition}`,+ );+ }++ /**+ * Truncate trace_attrs table after processing a chunk+ */+ private async truncateTraceAttrs(): Promise<void> {+ try {+ await commandClickhouse({+ query: `TRUNCATE TABLE trace_attrs`,+ tags: {+ feature: "background-migration",+ operation: "truncateTraceAttrs",+ },+ });+ logger.debug(`[Backfill Events] Truncated trace_attrs table`);+ } catch (error) {+ logger.error(+ `[Backfill Events] Failed to truncate trace_attrs, continuing anyway`,+ error,+ );+ // Don't fail the migration if truncate fails+ }+ }++ async validate(+ args: Record<string, unknown>,+ attempts = 5,+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {+ // Ensure the background migration record exists+ // TODO: Remove for golive+ await prisma.backgroundMigration.upsert({+ where: { id: backgroundMigrationId },+ create: {+ id: backgroundMigrationId,+ name: "20251027_backfill_events_historic",+ script: "backfillEventsHistoric",+ args: {},+ state: {},+ },+ update: {},+ });++ // 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 events table exists+ const tables = await clickhouseClient().query({+ query: "SHOW TABLES",+ });+ const tableNames = (await tables.json()).data as { name: string }[];++ if (!tableNames.some((r) => r.name === "events")) {+ // Retry if the table does not exist as this may mean migrations are still pending+ if (attempts > 0) {+ logger.info(+ `ClickHouse events table does not exist. Retrying in 10s...`,+ );+ return new Promise((resolve) => {+ setTimeout(() => resolve(this.validate(args, attempts - 1)), 10_000);+ });+ }++ return {+ valid: false,+ invalidReason: "ClickHouse events table does not exist",+ };+ }++ // Create trace_attrs table if it doesn't exist+ logger.info("[Backfill Events] Creating trace_attrs table if not exists");++ // TODO: Need to modify the engine for self-hosters or use actual migration logic.+ await commandClickhouse({+ query: `+ CREATE TABLE IF NOT EXISTS trace_attrs (+ project_id String,+ trace_id String,+ user_id String,+ session_id String,+ metadata Map(LowCardinality(String), String),+ event_ts DateTime64(3),+ is_deleted UInt8 DEFAULT 0+ ) ENGINE = ReplacingMergeTree(event_ts, is_deleted)+ ORDER BY (project_id, trace_id)+ `,+ tags: {+ feature: "background-migration",+ operation: "createTraceAttrsTable",+ },+ });++ logger.info("[Backfill Events] trace_attrs table ready");++ return { valid: true, invalidReason: undefined };+ }++ async run(args: Record<string, unknown>): Promise<void> {+ const start = Date.now();+ const migrationArgs = args as MigrationArgs;+ const targetChunkSize = parseInt(+ migrationArgs.targetChunkSize ?? "20_000_000",+ );+ const maxModulo = parseInt(migrationArgs.maxModulo ?? "512");+ const batchTimeoutMs = parseInt(migrationArgs.batchTimeoutMs ?? "7200000");++ logger.info(+ `[Backfill Events] Starting historic event backfill with args: ${JSON.stringify({ targetChunkSize, maxModulo, batchTimeoutMs })}`,+ );++ // Load or initialize state+ let state = await this.loadState();++ // Discover all partitions if this is the first run+ if (Object.keys(state.partitions).length === 0) {+ const partitions = await this.discoverPartitions();++ if (partitions.length === 0) {+ logger.info("[Backfill Events] No partitions found to process");+ return;+ }++ // Initialize state with discovered partitions+ for (const partition of partitions) {+ state.partitions[partition] = {+ modulo: 0, // Will be calculated when processing starts+ rowCount: 0,+ chunksProcessed: [],+ lastUpdated: new Date().toISOString(),+ };+ }++ state.currentPartition = partitions[0]; // Start with newest+ await this.updateState(state);+ logger.info(+ `[Backfill Events] Initialized state with ${partitions.length} partitions`,+ );+ }++ // Main processing loop+ while (!this.isAborted) {+ // Reload state to get latest progress+ state = await this.loadState();++ // Get current partition to process+ const currentPartition = state.currentPartition;++ if (!currentPartition) {+ logger.info(+ "[Backfill Events] All partitions processed. Migration complete!",+ );+ break;+ }++ const partitionState = state.partitions[currentPartition];++ if (!partitionState) {+ logger.error(+ `[Backfill Events] Partition ${currentPartition} not found in state`,+ );+ break;+ }++ // Initialize partition if modulo not calculated yet+ if (partitionState.modulo === 0) {+ const rowCount = await this.countPartitionRows(currentPartition);+ const modulo = this.calculateModulo(+ rowCount,+ targetChunkSize,+ maxModulo,+ );++ partitionState.rowCount = rowCount;+ partitionState.modulo = modulo;+ partitionState.lastUpdated = new Date().toISOString();++ await this.updateState(state);++ logger.info(+ `[Backfill Events] Partition ${currentPartition}: ${rowCount.toLocaleString()} rows → modulo ${modulo} (${modulo} chunks of ~${Math.floor(rowCount / modulo).toLocaleString()} rows each)`,+ );+ }++ // Get next chunk to process+ const nextChunk = this.getNextChunkToProcess(partitionState);++ if (nextChunk === null) {+ // All chunks processed for this partition+ logger.info(+ `[Backfill Events] Partition ${currentPartition}: all chunks complete`,+ );++ // Mark as completed and move to next partition+ if (!state.completedPartitions.includes(currentPartition)) {+ state.completedPartitions.push(currentPartition);+ }++ // Find next partition to process+ const allPartitions = Object.keys(state.partitions).sort().reverse();+ const currentIndex = allPartitions.indexOf(currentPartition);++ state.currentPartition =+ currentIndex < allPartitions.length - 1+ ? allPartitions[currentIndex + 1]+ : null;+ await this.updateState(state);+ continue;+ }++ // Process the chunk: trace_attrs -> events -> truncate+ try {+ // Step 1: Fill trace_attrs for this chunk+ await this.processTraceAttrsChunk(+ currentPartition,+ nextChunk,+ partitionState.modulo,+ batchTimeoutMs,+ );++ // Step 2: Fill events for this chunk (joining with trace_attrs)+ await this.processEventsChunk(+ currentPartition,+ nextChunk,+ partitionState.modulo,+ batchTimeoutMs,+ );++ // Step 3: Truncate trace_attrs to free memory+ await this.truncateTraceAttrs();++ // Mark chunk as completed+ partitionState.chunksProcessed.push(nextChunk);+ partitionState.lastUpdated = new Date().toISOString();+ await this.updateState(state);++ logger.info(+ `[Backfill Events] Partition ${currentPartition}: ${partitionState.chunksProcessed.length}/${partitionState.modulo} chunks complete`,+ );+ } catch (error) {+ logger.error(+ `[Backfill Events] Error processing chunk ${nextChunk} for partition ${currentPartition}`,+ error,+ );+ throw error; // Let the background migration manager handle the error+ }+ }++ if (this.isAborted) {+ logger.info(+ `[Backfill Events] Migration aborted. Can be resumed from current state.`,+ );+ return;+ }++ logger.info(+ `[Backfill Events] Finished historic event backfill in ${((Date.now() - start) / 1000 / 60).toFixed(2)} minutes`,+ );+ }++ async abort(): Promise<void> {+ logger.info("[Backfill Events] Aborting historic event backfill");+ this.isAborted = true;+ }+}++async function main() {+ const args = parseArgs({+ options: {+ targetChunkSize: { type: "string", short: "s", default: "20000000" },+ maxModulo: { type: "string", short: "m", default: "512" },+ batchTimeoutMs: {+ type: "string",+ short: "t",+ default: "7200000",+ },+ },+ });++ const migration = new BackfillEventsHistoric();+ 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/features/eventPropagation/EVENT_BACKFILL_HISTORIC_SETUP.md b/worker/src/features/eventPropagation/EVENT_BACKFILL_HISTORIC_SETUP.mddeleted file mode 100644index 699aa63de3..0000000000--- a/worker/src/features/eventPropagation/EVENT_BACKFILL_HISTORIC_SETUP.md+++ /dev/null@@ -1,290 +0,0 @@-# Historic Event Table Backfill--In this document, we track approaches on how to do the historic backfill for the event table.-We need to add trace information (metadata, userId, sessionId) onto all observations and insert them into the new-events table.--To manage the backfill, we process by partition (`YYYYMM`) and, in addition, separate each partition into multiple chunks.-For this purpose, we compute a hash over the projectId to ensure that all observations in a project are processed together.-When we go back in time to lower volume month, we can continue to decrease the number of chunks if the ClickHouse resources-can handle the query.--## Query--```sql- WITH relevant_keys AS (- select distinct project_id, trace_id- from observations- WHERE _partition_id = '202509'- AND (xxHash32(trace_id) % 256) = 1-), relevant_traces AS (- select- t.id as trace_id,- t.project_id,- t.user_id,- t.session_id,- mapFilter((k,v) -> NOT in(k, ['attributes']), t.metadata) AS metadata- from traces t- left semi join relevant_keys rk- on t.project_id = rk.project_id and t.id = rk.trace_id- where (xxHash32(t.id) % 256) = 1- order by t.project_id, toDate(t.timestamp), t.id, t.event_ts desc- limit 1 by t.project_id, t.id- )-- INSERT INTO events (- project_id,- trace_id,- span_id,- parent_span_id,- start_time,- end_time,- name,- type,- environment,- version,- user_id,- session_id,- level,- status_message,- completion_start_time,- prompt_id,- prompt_name,- prompt_version,- model_id,- provided_model_name,- model_parameters,- provided_usage_details,- usage_details,- provided_cost_details,- cost_details,- total_cost,- input,- output,- metadata,- metadata_names,- metadata_values,- source,- blob_storage_file_path,- event_raw,- event_bytes,- created_at,- updated_at,- event_ts,- is_deleted- )-- SELECT- o.project_id,- o.trace_id,- o.id AS span_id,- if(o.id = o.trace_id, NULL, coalesce(o.parent_observation_id, concat('t-', o.trace_id))) AS parent_span_id,- greatest(o.start_time, toDateTime64('1970-01-01', 3)) AS start_time,- o.end_time,- o.name,- o.type,- o.environment,- o.version,- coalesce(t.user_id, '') AS user_id,- coalesce(t.session_id, '') AS session_id,- o.level,- coalesce(o.status_message, '') AS status_message,- o.completion_start_time,- o.prompt_id,- o.prompt_name,- CAST(o.prompt_version, 'Nullable(String)') AS prompt_version,- o.internal_model_id AS model_id,- o.provided_model_name,- o.model_parameters,- o.provided_usage_details,- o.usage_details,- o.provided_cost_details,- o.cost_details,- coalesce(o.total_cost, 0) AS total_cost,- coalesce(o.input, '') AS input,- coalesce(o.output, '') AS output,- CAST(mapConcat(o.metadata, coalesce(t.metadata, map())), 'JSON') AS metadata,- mapKeys(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_names,- mapValues(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_values,- multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,- '' AS blob_storage_file_path,- '' AS event_raw,- byteSize(*) AS event_bytes,- o.created_at,- o.updated_at,- o.event_ts,- o.is_deleted- FROM observations AS o- LEFT JOIN relevant_traces AS t ON (o.project_id = t.project_id) AND (o.trace_id = t.trace_id)- WHERE (o._partition_id = '202509') AND ((xxHash32(t.trace_id) % 256) = 1)-- SETTINGS- -- join_algorithm = 'partial_merge',- min_insert_block_size_bytes = '512Mi',- parallel_distributed_insert_select = 2,- enable_parallel_replicas = 1,- -- allow_experimental_parallel_reading_from_replicas = 1,- -- max_parallel_replicas = 3,- type_json_skip_duplicated_paths = 1;-```--## Misc / Utils--### Create a mapping table and use if for joins directly instead of filtering/deduplicating on write--```sql-CREATE TABLE IF NOT EXISTS trace_attrs-(- project_id String,- trace_id String,-- -- Stable attributes you need on events- user_id String,- session_id String,- metadata Map(LowCardinality(String), String),-- -- Versioning columns for ReplacingMergeTree- event_ts DateTime64(3),- is_deleted UInt8 DEFAULT 0,-)-ENGINE = ReplacingMergeTree(event_ts, is_deleted)-ORDER BY (project_id, trace_id);--INSERT INTO trace_attrs-SELECT- t.project_id,- t.id AS trace_id,- t.user_id,- t.session_id,- mapFilter((k,v) -> NOT in(k, ['attributes','debug_info']), t.metadata) AS metadata,- t.event_ts,- 0 AS is_deleted-FROM traces AS t FINAL -- deduplicate before writing!-WHERE t.is_deleted = 0-AND _partition_id = '202509'-SETTINGS- max_insert_threads = 16,- min_insert_block_size_rows = 10048576;---INSERT INTO events (- project_id,- trace_id,- span_id,- parent_span_id,- start_time,- end_time,- name,- type,- environment,- version,- user_id,- session_id,- level,- status_message,- completion_start_time,- prompt_id,- prompt_name,- prompt_version,- model_id,- provided_model_name,- model_parameters,- provided_usage_details,- usage_details,- provided_cost_details,- cost_details,- total_cost,- input,- output,- metadata,- metadata_names,- metadata_values,- source,- blob_storage_file_path,- event_raw,- event_bytes,- created_at,- updated_at,- event_ts,- is_deleted-)-SELECT -- count(*)- o.project_id,- o.trace_id,- o.id AS span_id,- if(o.id = o.trace_id, NULL, coalesce(o.parent_observation_id, concat('t-', o.trace_id))) AS parent_span_id,- greatest(o.start_time, toDateTime64('1970-01-01', 3)) AS start_time,- o.end_time,- o.name,- o.type,- o.environment,- o.version,- coalesce(t.user_id, '') AS user_id,- coalesce(t.session_id, '') AS session_id,- o.level,- coalesce(o.status_message, '') AS status_message,- o.completion_start_time,- o.prompt_id,- o.prompt_name,- CAST(o.prompt_version, 'Nullable(String)') AS prompt_version,- o.internal_model_id AS model_id,- o.provided_model_name,- o.model_parameters,- o.provided_usage_details,- o.usage_details,- o.provided_cost_details,- o.cost_details,- coalesce(o.total_cost, 0) AS total_cost,- coalesce(o.input, '') AS input,- coalesce(o.output, '') AS output,- CAST(mapConcat(o.metadata, coalesce(t.metadata, map())), 'JSON') AS metadata,- mapKeys(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_names,- mapValues(mapConcat(o.metadata, coalesce(t.metadata, map()))) AS metadata_values,- multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel', 'ingestion-api') AS source,- '' AS blob_storage_file_path,- '' AS event_raw,- 0 AS event_bytes,- o.created_at,- o.updated_at,- o.event_ts,- o.is_deleted-FROM observations o-LEFT JOIN trace_attrs t-ON o.project_id = t.project_id AND o.trace_id = t.trace_id-WHERE o._partition_id = '202509'- AND (xxHash32(o.trace_id) % 128) = 1-SETTINGS- join_algorithm = 'partial_merge',- min_insert_block_size_bytes = '512Mi',- parallel_distributed_insert_select = 2,- enable_parallel_replicas = 1,- -- allow_experimental_parallel_reading_from_replicas = 1,- -- max_parallel_replicas = 3,- type_json_skip_duplicated_paths = 1;-```--### Remove full text indexes for faster ingest--```sql--- Drop Full Text indexes for faster ingest-ALTER TABLE events- DROP INDEX idx_fts_input_1,- DROP INDEX idx_fts_input_2,- DROP INDEX idx_fts_input_4,- DROP INDEX idx_fts_input_8,- DROP INDEX idx_fts_output_1,- DROP INDEX idx_fts_output_2,- DROP INDEX idx_fts_output_4,- DROP INDEX idx_fts_output_8;-```--### Check progress on a running query--```sql--- Check the progress-select elapsed, read_rows, read_bytes, total_rows_approx, written_rows, written_bytes,- memory_usage, peak_memory_usage, ProfileEvents, Settings-from clusterAllReplicas('default', 'system.processes')-where query_id = '<uuid>'-format vertical;-```\ No newline at end of filediff --git a/worker/src/features/eventPropagation/EVENT_BACKFILL_VALIDATION_QUERIES.md b/worker/src/features/eventPropagation/EVENT_BACKFILL_VALIDATION_QUERIES.mddeleted file mode 100644index 180d0f243a..0000000000--- a/worker/src/features/eventPropagation/EVENT_BACKFILL_VALIDATION_QUERIES.md+++ /dev/null@@ -1,493 +0,0 @@-# Event Backfill Validation Queries--## Query 1: Coverage & Count Validation--```sql-WITH- -- Time range configuration- time_range AS (- SELECT- toDateTime('2025-10-21 08:57:00') AS min_time,- toDateTime('2025-10-21 11:51:00') AS max_time- ),-- -- Get filtered observations- filtered_obs AS (- SELECT *- FROM observations- WHERE start_time >= (SELECT min_time FROM time_range)- AND start_time <= (SELECT max_time FROM time_range)- ),-- -- Get filtered events- filtered_events AS (- SELECT *- FROM events e- WHERE start_time >= (SELECT min_time FROM time_range)- AND start_time <= (SELECT max_time FROM time_range)- and e.source = 'ingestion-api'- ),-- -- Overall counts- overall_counts AS (- SELECT- 'OVERALL' AS category,- '' AS dimension,- (SELECT count() FROM filtered_obs) AS obs_count,- (SELECT count() FROM filtered_events) AS event_count,- (SELECT count() FROM observations_batch_staging) AS staging_count- ),-- -- Counts by project- project_counts AS (- SELECT- 'BY_PROJECT' AS category,- o.project_id AS dimension,- count() AS obs_count,- countIf(e.span_id IS NOT NULL) AS event_count,- 0 AS staging_count- FROM filtered_obs o- LEFT JOIN filtered_events e ON o.id = e.span_id AND o.project_id = e.project_id- GROUP BY o.project_id- )--SELECT- category,- dimension,- obs_count,- event_count,- staging_count,- obs_count - event_count AS missing_in_events,- CASE- WHEN obs_count > 0 THEN round((event_count / obs_count) * 100, 2)- ELSE 0- END AS coverage_pct,- CASE- WHEN category = 'OVERALL' AND staging_count + event_count >= obs_count * 0.99 THEN '✓ PASS'- WHEN category != 'OVERALL' AND event_count >= obs_count * 0.99 THEN '✓ PASS'- WHEN category != 'OVERALL' AND event_count >= obs_count * 0.95 THEN '⚠WARN'- ELSE '✗ FAIL'- END AS status-FROM overall_counts-UNION ALL-SELECT category, dimension, obs_count, event_count, staging_count,- obs_count - event_count,- CASE WHEN obs_count > 0 THEN round((event_count / obs_count) * 100, 2) ELSE 0 END,- CASE- WHEN event_count >= obs_count * 0.99 THEN '✓ PASS'- WHEN event_count >= obs_count * 0.95 THEN '⚠WARN'- ELSE '✗ FAIL'- END-FROM project_counts-ORDER BY- CASE category- WHEN 'OVERALL' THEN 1- WHEN 'BY_PROJECT' THEN 2- END,- 7;-```--## Query 2: Field Mapping Validation--```sql--WITH- -- Time range configuration- time_range AS (- SELECT- toDateTime('2025-10-21 08:57:00') AS min_time,- toDateTime('2025-10-21 11:51:00') AS max_time- ),-- sampled_projects AS (- SELECT project_id- FROM observations o- WHERE o.start_time >= (SELECT min_time FROM time_range)- AND o.start_time <= (SELECT max_time FROM time_range)- ORDER BY rand()- LIMIT 10- ),-- -- Join observations with events- obs_event_joined AS (- SELECT- o.id,- o.project_id,- o.trace_id,- o.parent_observation_id,- o.start_time AS o_start_time,- o.end_time AS o_end_time,- o.completion_start_time AS o_completion_start_time,- o.name AS o_name,- o.type AS o_type,- o.environment AS o_environment,- o.version AS o_version,- o.level AS o_level,- o.status_message AS o_status_message,- o.input AS o_input,- o.output AS o_output,- o.metadata AS o_metadata,- e.span_id AS e_span_id,- e.parent_span_id AS e_parent_span_id,- e.trace_id AS e_trace_id,- e.start_time AS e_start_time,- e.end_time AS e_end_time,- e.completion_start_time AS e_completion_start_time,- e.metadata_names AS e_metadata_names,- e.name AS e_name,- e.type AS e_type,- e.environment AS e_environment,- e.version AS e_version,- e.level AS e_level,- e.status_message AS e_status_message,- e.input AS e_input,- e.output AS e_output- FROM observations o- LEFT JOIN events e- ON o.id = e.span_id AND o.project_id = e.project_id- WHERE o.start_time >= (SELECT min_time FROM time_range)- AND o.start_time <= (SELECT max_time FROM time_range)- and e.start_time >= (SELECT min_time FROM time_range)- and e.start_time <= (SELECT max_time FROM time_range)- and o.project_id in (select project_id from sampled_projects)- and e.source = 'ingestion-api'- )---- Identifier mismatches-SELECT- 'IDENTIFIER_MAPPINGS' AS validation_category,- 'parent_span_id_mismatch' AS issue_type,- id AS observation_id,- project_id,- coalesce(parent_observation_id, concat('t-', trace_id)) AS obs_value,- e_parent_span_id AS event_value-FROM obs_event_joined-WHERE e_parent_span_id != coalesce(parent_observation_id, concat('t-', trace_id))--UNION ALL--SELECT- 'IDENTIFIER_MAPPINGS' AS validation_category,- 'trace_id_mismatch' AS issue_type,- id AS observation_id,- project_id,- trace_id AS obs_value,- e_trace_id AS event_value-FROM obs_event_joined-WHERE e_trace_id != trace_id---- Timestamp mismatches-UNION ALL--SELECT- 'TIMESTAMP_MAPPINGS' AS validation_category,- 'start_time_mismatch' AS issue_type,- id AS observation_id,- project_id,- toString(o_start_time) AS obs_value,- toString(e_start_time) AS event_value-FROM obs_event_joined-WHERE toStartOfInterval(o_start_time, INTERVAL 1 SECOND) != toStartOfInterval(e_start_time, INTERVAL 1 SECOND)--UNION ALL--SELECT- 'TIMESTAMP_MAPPINGS' AS validation_category,- 'end_time_mismatch' AS issue_type,- id AS observation_id,- project_id,- toString(o_end_time) AS obs_value,- toString(e_end_time) AS event_value-FROM obs_event_joined-WHERE o_end_time IS NOT NULL- AND e_end_time IS NOT NULL- AND toStartOfInterval(o_end_time, INTERVAL 1 SECOND) != toStartOfInterval(e_end_time, INTERVAL 1 SECOND)--UNION ALL--SELECT- 'TIMESTAMP_MAPPINGS' AS validation_category,- 'end_time_null_mismatch' AS issue_type,- id AS observation_id,- project_id,- 'NULL' AS obs_value,- toString(e_end_time) AS event_value-FROM obs_event_joined-WHERE o_end_time IS NULL AND e_end_time IS NOT NULL---- Core string field mismatches-UNION ALL--SELECT- 'CORE_STRING_FIELDS' AS validation_category,- 'name_mismatch' AS issue_type,- id AS observation_id,- project_id,- o_name AS obs_value,- e_name AS event_value-FROM obs_event_joined-WHERE o_name != e_name--UNION ALL--SELECT- 'CORE_STRING_FIELDS' AS validation_category,- 'type_mismatch' AS issue_type,- id AS observation_id,- project_id,- o_type AS obs_value,- e_type AS event_value-FROM obs_event_joined-WHERE o_type != e_type--UNION ALL--SELECT- 'CORE_STRING_FIELDS' AS validation_category,- 'level_mismatch' AS issue_type,- id AS observation_id,- project_id,- o_level AS obs_value,- e_level AS event_value-FROM obs_event_joined-WHERE o_level != e_level---- Nullable string field mismatches-UNION ALL--SELECT- 'NULLABLE_STRING_FIELDS' AS validation_category,- 'status_message_mismatch' AS issue_type,- id AS observation_id,- project_id,- coalesce(o_status_message, '') AS obs_value,- e_status_message AS event_value-FROM obs_event_joined-WHERE coalesce(o_status_message, '') != e_status_message--UNION ALL--SELECT- 'NULLABLE_STRING_FIELDS' AS validation_category,- 'version_mismatch' AS issue_type,- id AS observation_id,- project_id,- coalesce(o_version, '') AS obs_value,- coalesce(e_version, '') AS event_value-FROM obs_event_joined-WHERE coalesce(o_version, '') != coalesce(e_version, '')--UNION ALL--SELECT- 'NULLABLE_STRING_FIELDS' AS validation_category,- 'environment_mismatch' AS issue_type,- id AS observation_id,- project_id,- o_environment AS obs_value,- e_environment AS event_value-FROM obs_event_joined-WHERE o_environment != e_environment--UNION ALL--SELECT- 'INPUT_OUTPUT_FIELDS' AS validation_category,- 'input_mismatch' AS issue_type,- id AS observation_id,- project_id,- o_input AS obs_value,- e_input AS event_value-FROM obs_event_joined-WHERE o_input != e_input--UNION ALL--SELECT- 'INPUT_OUTPUT_FIELDS' AS validation_category,- 'output_mismatch' AS issue_type,- id AS observation_id,- project_id,- o_output AS obs_value,- e_output AS event_value-FROM obs_event_joined-WHERE o_output != e_output--UNION ALL--SELECT- 'METADATA_FIELD' AS validation_category,- 'metadata_key_mismatch' AS issue_type,- id AS observation_id,- project_id,- arrayStringConcat(mapKeys(o_metadata), ', ') AS obs_value,- arrayStringConcat(e_metadata_names, ', ') AS event_value-FROM obs_event_joined-WHERE NOT arrayAll(k -> has(e_metadata_names, k), mapKeys(o_metadata))---- ORDER BY validation_category, issue_type, observation_id-SETTINGS join_algorithm = 'partial_merge'-```--## Query 3: Trace Join & User/Session/Metadata Propagation--```sql-WITH- -- Time range configuration- time_range AS (- SELECT- toDateTime('2025-10-21 08:57:00') AS min_time,- toDateTime('2025-10-21 11:51:00') AS max_time- ),-- sampled_projects AS (- SELECT project_id- FROM observations o- WHERE o.start_time >= (SELECT min_time FROM time_range)- AND o.start_time <= (SELECT max_time FROM time_range)- ORDER BY rand()- LIMIT 10- ),-- -- Join events and traces- full_join AS (- SELECT- e.span_id as span_id,- e.project_id as project_id,- e.trace_id as trace_id,- t.user_id AS t_user_id,- t.session_id AS t_session_id,- t.metadata AS t_metadata,- e.user_id AS e_user_id,- e.session_id AS e_session_id,- e.metadata_names AS e_metadata_names- FROM traces t- LEFT JOIN events e- ON e.trace_id = t.id- AND e.project_id = t.project_id- WHERE e.start_time >= (SELECT min_time FROM time_range)- AND e.start_time <= (SELECT max_time FROM time_range)- AND t.timestamp >= (SELECT min_time FROM time_range)- AND t.timestamp <= (SELECT max_time FROM time_range)- and t.project_id IN (SELECT project_id FROM sampled_projects)- and e.project_id IN (SELECT project_id FROM sampled_projects)- AND e.source = 'ingestion-api'- )--SELECT- 'user_id_mismatch' AS issue_type,- span_id,- project_id,- t_user_id AS obs_value,- e_user_id AS event_value-FROM full_join-WHERE t_user_id != e_user_id--UNION ALL--SELECT- 'session_id_mismatch' AS issue_type,- span_id,- project_id,- t_session_id AS obs_value,- e_session_id AS event_value-FROM full_join-WHERE t_session_id != e_session_id--UNION ALL--SELECT- 'metadata_keys_missing' AS issue_type,- span_id,- project_id,- arrayStringConcat(mapKeys(t_metadata), ', ') AS obs_value,- arrayStringConcat(e_metadata_names, ', ') AS event_value-FROM full_join-WHERE NOT arrayAll(k -> has(e_metadata_names, k), mapKeys(t_metadata))-- SETTINGS join_algorithm = 'partial_merge'-```--## Query 4: Root Span Validation--```sql-WITH- -- Time range configuration- time_range AS (- SELECT- toDateTime('2025-10-17 09:00:00') AS min_time,- toDateTime('2025-10-17 13:45:00') AS max_time- ),-- sampled_projects AS (- SELECT project_id- FROM observations o- WHERE o.start_time >= (SELECT min_time FROM time_range)- AND o.start_time <= (SELECT max_time FROM time_range)- ORDER BY rand()- LIMIT 10- ),-- -- Join with events to find root spans- root_span_check AS (- SELECT- t.project_id,- t.id AS trace_id,- t.name AS trace_name,- e.span_id AS root_span_id,- e.parent_span_id AS root_parent_span_id,- e.name AS root_span_name- FROM traces t- LEFT JOIN events e- ON t.project_id = e.project_id- AND e.trace_id = t.id- AND e.parent_span_id = ''- AND e.start_time >= (SELECT min_time FROM time_range)- AND e.start_time <= (SELECT max_time FROM time_range)- WHERE t.project_id IN (SELECT project_id FROM sampled_projects)- AND t.timestamp >= (SELECT min_time FROM time_range)- AND t.timestamp <= (SELECT max_time FROM time_range)- AND (e.source is NULL or e.source = 'ingestion-api')- )---- Missing root spans-SELECT- 'missing_root_span' AS issue_type,- project_id,- trace_id,- trace_name AS expected_name,- concat('t-', trace_id) AS expected_span_id,- '' AS actual_value-FROM root_span_check-WHERE root_span_id IS NULL--UNION ALL---- Root spans with non-null parent_span_id-SELECT- 'root_span_has_parent' AS issue_type,- project_id,- trace_id,- trace_name AS expected_name,- root_span_id AS expected_span_id,- root_parent_span_id AS actual_value-FROM root_span_check-WHERE root_span_id IS NOT NULL- AND root_parent_span_id != ''--UNION ALL---- Root spans with name mismatch-SELECT- 'root_span_name_mismatch' AS issue_type,- project_id,- trace_id,- trace_name AS expected_name,- root_span_id AS expected_span_id,- root_span_name AS actual_value-FROM root_span_check-WHERE root_span_id IS NOT NULL- AND root_span_name != trace_name--SETTINGS join_algorithm = 'partial_merge'-```