🪢 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: create update backfill script based on sorted chunks (#10702)
Steffen Schmitz4258621ed036
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex 1107458a8b..40fab040f9 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -317,7 +317,7 @@ function handleExceptionRow<T>(parsedRow: T): T {}/**- * Determines if an error is retryable (socket hang up, connection reset, etc.)+ * Determines if an error is retryable (socket hang up, connection reset, broken pipe, etc.)*/function isRetryableError(error: unknown): boolean {if (!error || typeof error !== "object") return false;@@ -325,7 +325,17 @@ function isRetryableError(error: unknown): boolean {const errorMessage = (error as Error).message?.toLowerCase() || "";// Check for socket hang up and other network-related errors- return errorMessage.includes("socket hang up");+ const retryablePatterns = [+ "socket hang up",+ "broken pipe",+ "connection reset",+ "econnreset",+ "network_error",+ "etimedout",+ "econnrefused",+ ];++ return retryablePatterns.some((pattern) => errorMessage.includes(pattern));}export async function queryClickhouse<T>(opts: {@@ -448,6 +458,9 @@ export async function commandClickhouse(opts: {const res = await clickhouseClient(opts.clickhouseConfigs).command({query: opts.query,query_params: opts.params,+ ...(opts.tags?.queryId+ ? { query_id: opts.tags.queryId as string }+ : {}),clickhouse_settings: {...opts.clickhouseSettings,log_comment: JSON.stringify(opts.tags ?? {}),diff --git a/worker/src/backgroundMigrations/backfillEventsHistoric.ts b/worker/src/backgroundMigrations/backfillEventsHistoric.tsindex 4f8214d9f0..a54fbcffe4 100644--- a/worker/src/backgroundMigrations/backfillEventsHistoric.ts+++ b/worker/src/backgroundMigrations/backfillEventsHistoric.ts@@ -8,118 +8,267 @@ import {import { prisma } from "@langfuse/shared/src/db";import { env } from "../env";import { parseArgs } from "node:util";--// TODO: This is WIP and should not be used for actual backfills.+import { randomUUID } from "crypto";// This is hard-coded in our migrations and uniquely identifies the row in background_migrations tableconst 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;+// ============================================================================+// Types+// ============================================================================++interface ChunkTodo {+ id: string; // Unique chunk identifier (e.g., "obs-202510-0")+ partition: string; // ClickHouse partition (e.g., "202510")+ lowerBound: { projectId: string; traceId: string }; // From backfill_chunks table+ upperBound: { projectId: string; traceId: string } | null; // null = end of partition+ status: "pending" | "in_progress" | "completed" | "failed";+ queryId?: string; // Client-generated UUID for tracking in system.query_log+ startedAt?: string;+ completedAt?: string;+ error?: string;+ retryCount?: number;}-interface MigrationState {- partitions: Record<string, PartitionState>;- currentPartition: string | null;- completedPartitions: string[];+interface MigrationArgs {+ concurrency?: number; // Default: 4+ pollIntervalMs?: number; // Default: 30_000+ maxRetries?: number; // Default: 3+ batchTimeoutMs?: number; // Default: 7_200_000 (2h)+ retryFailed?: boolean; // Reset failed chunks to pending}-interface MigrationArgs {- targetChunkSize?: string; // Default: 20_000_000- maxModulo?: string; // Default: 512- batchTimeoutMs?: string; // Default: 7_200_000 (2h)+interface MigrationState {+ phase: "init" | "loading_chunks" | "backfill" | "completed";+ chunksLoaded: boolean; // Whether chunks have been loaded from backfill_chunks+ todos: ChunkTodo[];+ activeQueries: string[]; // Currently running query IDs+ config: MigrationArgs;}-export default class BackfillEventsHistoric implements IBackgroundMigration {- private isAborted = false;+const DEFAULT_CONFIG: MigrationState["config"] = {+ concurrency: 4,+ pollIntervalMs: 30_000,+ maxRetries: 3,+ batchTimeoutMs: 7_200_000,+};++type OnQueryCompleteCallback = (+ // eslint-disable-next-line no-unused-vars+ todo: ChunkTodo,+ // eslint-disable-next-line no-unused-vars+ success: boolean,+ // eslint-disable-next-line no-unused-vars+ error?: string,+) => Promise<void>;++// ============================================================================+// Query Status Polling+// ============================================================================++type QueryStatus = "running" | "completed" | "failed" | "not_found";++async function pollQueryStatus(queryId: string): Promise<QueryStatus> {+ // First check if still running in system.processes+ const running = await queryClickhouse<{ query_id: string }>({+ query: `+ SELECT query_id+ FROM clusterAllReplicas('default', 'system.processes')+ WHERE query_id = {queryId: String}+ LIMIT 1+ `,+ params: { queryId },+ clickhouseSettings: {+ skip_unavailable_shards: 1,+ },+ tags: {+ feature: "background-migration",+ operation: "pollQueryStatus-processes",+ },+ });- /**- * 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)));+ if (running.length > 0) {+ return "running";}- /**- * 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));- }+ // Check query_log for completion status+ const result = await queryClickhouse<{+ type: string;+ exception_code: string;+ }>({+ query: `+ SELECT type, exception_code+ FROM clusterAllReplicas('default', 'system.query_log')+ WHERE query_id = {queryId: String}+ -- AND type != 'QueryStart'+ ORDER BY event_time_microseconds DESC+ LIMIT 1+ `,+ params: { queryId },+ clickhouseSettings: {+ skip_unavailable_shards: 1,+ },+ tags: {+ feature: "background-migration",+ operation: "pollQueryStatus-queryLog",+ },+ });- /**- * Discover all partitions from observations table, ordered newest to oldest- */- private async discoverPartitions(): Promise<string[]> {- logger.info("[Backfill Events] Discovering partitions from observations");+ if (result.length === 0) {+ return "not_found";+ }- 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 { type, exception_code } = result[0];+ if (type === "QueryStart") {+ return "running";+ }- const partitions = result.map((r) => r.partition);- logger.info(- `[Backfill Events] Discovered ${partitions.length} partitions: ${partitions.join(", ")}`,- );+ if (+ type === "ExceptionBeforeStart" ||+ type === "ExceptionWhileProcessing" ||+ parseInt(exception_code, 10) !== 0+ ) {+ return "failed";+ }- return partitions;+ if (type === "QueryFinish") {+ return "completed";}- /**- * Count rows in a specific partition- */- private async countPartitionRows(partition: string): Promise<number> {- logger.info(`[Backfill Events] Counting rows in partition ${partition}`);+ throw new Error(`Unknown query log type: ${type}`);+}- 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,- },- });+async function getQueryError(queryId: string): Promise<string | undefined> {+ const result = await queryClickhouse<{ exception: string }>({+ query: `+ SELECT exception+ FROM clusterAllReplicas('default', 'system.query_log')+ WHERE query_id = {queryId: String}+ AND type != 'QueryStart'+ AND exception != ''+ ORDER BY event_time_microseconds DESC+ LIMIT 1+ `,+ params: { queryId },+ clickhouseSettings: {+ skip_unavailable_shards: 1,+ },+ tags: {+ feature: "background-migration",+ operation: "getQueryError",+ },+ });- const count = parseInt(result[0]?.count ?? "0", 10);- logger.info(- `[Backfill Events] Partition ${partition} has ${count.toLocaleString()} rows`,- );+ return result[0]?.exception;+}++// ============================================================================+// Concurrent Query Manager+// ============================================================================++class ConcurrentQueryManager {+ private activeQueries: Map<string, ChunkTodo> = new Map();+ private pollInterval: NodeJS.Timeout | null = null;+ private isPolling = false;++ startPolling(+ pollIntervalMs: number,+ onComplete: OnQueryCompleteCallback,+ scheduleNext: () => Promise<void>,+ ): void {+ if (this.pollInterval) {+ return; // Already polling+ }++ this.pollInterval = setInterval(async () => {+ if (this.isPolling) return; // Skip if previous poll still running+ this.isPolling = true;++ try {+ for (const [queryId, todo] of this.activeQueries) {+ try {+ const status = await pollQueryStatus(queryId);++ if (status === "completed") {+ this.activeQueries.delete(queryId);+ await onComplete(todo, true);+ await scheduleNext(); // Immediately schedule next+ } else if (status === "failed" || status === "not_found") {+ this.activeQueries.delete(queryId);+ const error =+ status === "failed"+ ? await getQueryError(queryId)+ : "Query not found in query_log";+ await onComplete(todo, false, error);+ await scheduleNext();+ }+ // 'running' - continue polling+ } catch (queryError) {+ // Error while polling this specific query - treat as failure+ logger.error(+ `[Backfill Events] Error polling query ${queryId} for chunk ${todo.id}`,+ queryError,+ );+ this.activeQueries.delete(queryId);+ const errorMessage =+ queryError instanceof Error+ ? queryError.message+ : String(queryError);+ await onComplete(todo, false, errorMessage);+ await scheduleNext();+ }+ }+ } catch (error) {+ // Unexpected error outside individual query handling+ logger.error(+ "[Backfill Events] Unexpected error during poll cycle",+ error,+ );+ } finally {+ this.isPolling = false;+ }+ }, pollIntervalMs);+ }++ addQuery(todo: ChunkTodo, queryId: string): void {+ this.activeQueries.set(queryId, todo);+ }- return count;+ get activeCount(): number {+ return this.activeQueries.size;}- /**- * Load migration state from database- */+ stopPolling(): void {+ if (this.pollInterval) {+ clearInterval(this.pollInterval);+ this.pollInterval = null;+ }+ }+}++// ============================================================================+// Helper Functions+// ============================================================================++function generateQueryId(chunkId: string): string {+ return `backfill-${chunkId}-${randomUUID().slice(0, 8)}`;+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++// ============================================================================+// Migration Class+// ============================================================================++export default class BackfillEventsHistoric implements IBackgroundMigration {+ private isAborted = false;++ // ============================================================================+ // State Management+ // ============================================================================+private async loadState(): Promise<MigrationState> {const migration = await prisma.backgroundMigration.findUnique({where: { id: backgroundMigrationId },@@ -127,29 +276,31 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {});const defaultState: MigrationState = {- partitions: {},- currentPartition: null,- completedPartitions: [],+ phase: "init",+ chunksLoaded: false,+ todos: [],+ activeQueries: [],+ config: { ...DEFAULT_CONFIG },};if (!migration || !migration.state) {return defaultState;}- const state = migration.state as any;+ const state = migration.state as Partial<MigrationState>;- // Validate and merge with defaults to ensure all required fields existreturn {- partitions: state.partitions ?? defaultState.partitions,- currentPartition: state.currentPartition ?? defaultState.currentPartition,- completedPartitions:- state.completedPartitions ?? defaultState.completedPartitions,+ phase: state.phase ?? defaultState.phase,+ chunksLoaded: state.chunksLoaded ?? defaultState.chunksLoaded,+ todos: state.todos ?? defaultState.todos,+ activeQueries: state.activeQueries ?? defaultState.activeQueries,+ config: {+ ...DEFAULT_CONFIG,+ ...state.config,+ },};}- /**- * Update migration state in database- */private async updateState(state: MigrationState): Promise<void> {await prisma.backgroundMigration.update({where: { id: backgroundMigrationId },@@ -157,251 +308,329 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {});}- /**- * 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;+ // ============================================================================+ // Prerequisite Validation+ // ============================================================================++ private async validatePrerequisites(): Promise<{+ valid: boolean;+ reason?: string;+ }> {+ const requiredTables = [+ "observations_pid_tid_sorting",+ "traces_pid_tid_sorting",+ "events",+ "backfill_chunks",+ ];++ for (const table of requiredTables) {+ try {+ const result = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM ${table} LIMIT 1`,+ tags: {+ feature: "background-migration",+ operation: "validatePrerequisites",+ table,+ },+ });+ if (!result.length) {+ return { valid: false, reason: `${table} table does not exist` };+ }+ } catch {+ return {+ valid: false,+ reason: `${table} table does not exist or is not accessible`,+ };}}- return null; // All chunks processed+ // Verify backfill_chunks has data+ const chunksCount = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM backfill_chunks`,+ tags: {+ feature: "background-migration",+ operation: "validatePrerequisites",+ table: "backfill_chunks",+ },+ });+ if (chunksCount[0].count === "0") {+ return {+ valid: false,+ reason:+ "backfill_chunks table is empty - populate chunk boundaries first",+ };+ }++ return { valid: true };}- /**- * 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}`,- );+ // ============================================================================+ // Load Chunks from ClickHouse+ // ============================================================================++ private async loadChunksFromClickhouse(): Promise<ChunkTodo[]> {+ logger.info("[Backfill Events] Loading chunks from backfill_chunks table");- await commandClickhouse({+ const chunks = await queryClickhouse<{+ chunk_id: string;+ partition_id: string;+ project_id: string;+ trace_id: string;+ is_last_chunk: string;+ }>({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,- t.public,- t.bookmarked,- 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)+ SELECT chunk_id, partition_id, project_id, trace_id, is_last_chunk+ FROM backfill_chunks+ ORDER BY partition_id, chunk_id`,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",+ operation: "loadChunksFromClickhouse",},});+ const todos: ChunkTodo[] = [];++ // Group by partition and type to compute upper bounds+ const grouped = new Map<string, typeof chunks>();+ for (const chunk of chunks) {+ const key = chunk.partition_id;+ if (!grouped.has(key)) grouped.set(key, []);+ grouped.get(key)!.push(chunk);+ }++ for (const [, partitionChunks] of grouped) {+ for (let i = 0; i < partitionChunks.length; i++) {+ const chunk = partitionChunks[i];+ const nextChunk = partitionChunks[i + 1];+ const isLastChunk = chunk.is_last_chunk === "1";++ todos.push({+ id: chunk.chunk_id,+ partition: chunk.partition_id,+ lowerBound: { projectId: chunk.project_id, traceId: chunk.trace_id },+ upperBound:+ isLastChunk || !nextChunk+ ? null+ : {+ projectId: nextChunk.project_id,+ traceId: nextChunk.trace_id,+ },+ status: "pending",+ });+ }+ }+logger.info(- `[Backfill Events] Completed trace_attrs for chunk ${chunkId + 1}/${modulo} in partition ${partition}`,+ `[Backfill Events] Loaded ${todos.length} chunks from backfill_chunks table`,);++ return todos;}- /**- * Process a single chunk for the events phase- */- private async processEventsChunk(- partition: string,- chunkId: number,- modulo: number,- timeoutMs: number,- ): Promise<void> {+ // ============================================================================+ // Recovery Logic+ // ============================================================================++ private async recoverInProgressTodos(state: MigrationState): Promise<void> {+ const inProgress = state.todos.filter(+ (t) => t.status === "in_progress" && t.queryId,+ );++ if (inProgress.length === 0) {+ return;+ }+logger.info(- `[Backfill Events] Processing events for chunk ${chunkId + 1}/${modulo} in partition ${partition}`,+ `[Backfill Events] Recovering ${inProgress.length} in-progress chunks`,);- 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,- public,- bookmarked,- level,- status_message,- completion_start_time,- prompt_id,- prompt_name,- prompt_version,- model_id,- provided_model_name,- model_parameters,- provided_usage_details,- usage_details,- provided_cost_details,- cost_details,- input,- output,- metadata,- metadata_names,- metadata_raw_values,- source,- service_name,- service_version,- scope_name,- scope_version,- telemetry_sdk_language,- telemetry_sdk_name,- telemetry_sdk_version,- blob_storage_file_path,- event_bytes,- created_at,- updated_at,- event_ts,- is_deleted- )- 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,- o.start_time 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,- coalesce(t.public, false) AS public,- coalesce(t.bookmarked AND (o.parent_observation_id IS NULL OR o.parent_observation_id = ''), false) AS bookmarked,- o.level,- coalesce(o.status_message, '') AS status_message,- o.completion_start_time,- o.prompt_id,- o.prompt_name,- o.prompt_version,- o.internal_model_id AS model_id,- o.provided_model_name,- coalesce(o.model_parameters, '{}'),- o.provided_usage_details,- o.usage_details,- o.provided_cost_details,- o.cost_details,- 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_raw_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,- 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- `,+ for (const todo of inProgress) {+ const status = await pollQueryStatus(todo.queryId!);++ if (status === "completed") {+ todo.status = "completed";+ todo.completedAt = new Date().toISOString();+ logger.info(+ `[Backfill Events] Recovered chunk ${todo.id} as completed`,+ );+ } else if (status === "failed") {+ todo.status = "pending"; // Will retry+ todo.retryCount = (todo.retryCount || 0) + 1;+ const error = await getQueryError(todo.queryId!);+ logger.warn(+ `[Backfill Events] Recovered chunk ${todo.id} as failed, will retry: ${error}`,+ );+ } else {+ // not_found or running+ if (status === "not_found") {+ // Query never started or was lost+ todo.status = "pending";+ logger.warn(+ `[Backfill Events] Recovered chunk ${todo.id} as not_found, resetting to pending`,+ );+ }+ // If still running, we leave it as in_progress but clear queryId+ // so it doesn't interfere with new queries+ }+ }++ await this.updateState(state);+ }++ // ============================================================================+ // Query Building+ // ============================================================================++ private buildQuery(todo: ChunkTodo): string {+ const whereClause = todo.upperBound+ ? `WHERE (o.project_id, o.trace_id) >= ('${todo.lowerBound.projectId}', '${todo.lowerBound.traceId}')+ AND (o.project_id, o.trace_id) < ('${todo.upperBound.projectId}', '${todo.upperBound.traceId}')`+ : `WHERE (o.project_id, o.trace_id) >= ('${todo.lowerBound.projectId}', '${todo.lowerBound.traceId}')`;++ return `+ INSERT INTO events (+ project_id, trace_id, span_id, parent_span_id, start_time, end_time,+ name, type, environment, version, release, tags, public, bookmarked,+ 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, input, output, metadata,+ metadata_names, metadata_raw_values, source,+ blob_storage_file_path, 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,+ o.start_time AS start_time,+ o.end_time,+ o.name,+ o.type,+ o.environment,+ coalesce(o.version, t.version) as version,+ coalesce(t.release, '') as release,+ t.tags as tags,+ t.public as public,+ t.bookmarked as bookmarked,+ 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,+ o.prompt_version,+ o.internal_model_id AS model_id,+ o.provided_model_name,+ coalesce(o.model_parameters, '{}') AS model_parameters,+ o.provided_usage_details,+ o.usage_details,+ o.provided_cost_details,+ o.cost_details,+ coalesce(o.input, '') AS input,+ coalesce(o.output, '') AS output,+ metadata::JSON AS metadata,+ mapKeys(o.metadata) AS metadata_names,+ mapValues(o.metadata) AS metadata_raw_values,+ multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,+ '' AS blob_storage_file_path,+ 0 AS event_bytes,+ o.created_at,+ o.updated_at,+ o.event_ts,+ o.is_deleted+ FROM observations_pid_tid_sorting o+ LEFT ANY JOIN traces_pid_tid_sorting t+ ON o.project_id = t.project_id AND o.trace_id = t.id+ ${whereClause}+ -- Conditionally filter for partitions if not "REST"+ -- This allow us to have a catch all partition for older data+ ${todo.partition !== "REST" ? `AND o._partition_id = '${todo.partition}'` : ""}+ ${todo.partition !== "REST" ? `AND (t._partition_id = '${todo.partition}' OR t._partition_id IS NULL)` : ""}+ SETTINGS+ join_algorithm = 'full_sorting_merge',+ type_json_skip_duplicated_paths = 1+ `;+ }++ // ============================================================================+ // Fire Query (with tracking)+ // ============================================================================++ private async fireQuery(+ query: string,+ queryId: string,+ timeoutMs: number,+ retryCount: number = 0,+ ): Promise<void> {+ logger.info(`[Backfill Events] Firing query ${queryId}`);++ // Apply memory-reducing settings on retries+ const retrySettings =+ retryCount > 0+ ? {+ max_threads: 1,+ max_block_size: "32768",+ }+ : {};++ if (retryCount > 0) {+ logger.info(+ `[Backfill Events] Applying retry settings for query ${queryId}: max_threads=1, max_block_size=32768 (retry ${retryCount})`,+ );+ }++ // Fire the query - commandClickhouse will wait for completion+ // but we want to track it via polling instead+ const queryPromise = commandClickhouse({+ query,tags: {feature: "background-migration",- operation: "processEventsChunk",- partition,- chunkId: chunkId.toString(),+ operation: "fireQuery",+ queryId,},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",+ send_progress_in_http_headers: 1,+ http_headers_progress_interval_ms: "30000",+ ...retrySettings,},});- logger.info(- `[Backfill Events] Completed events for chunk ${chunkId + 1}/${modulo} in partition ${partition}`,- );- }+ // Wait a short time to ensure query is registered+ await sleep(5000);++ // Verify query is running on server+ const status = await pollQueryStatus(queryId);+ if (status === "not_found") {+ // Query may have completed very quickly or failed to start+ // Wait a bit more and check again+ await sleep(15000);+ const retryStatus = await pollQueryStatus(queryId);+ if (retryStatus === "not_found") {+ throw new Error(`Query ${queryId} failed to start on server`);+ }+ }- /**- * 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 await the promise - we'll track via polling+ // The promise will resolve when the query completes+ queryPromise.catch((err) => {+ // Log but don't throw - we track completion via polling+ logger.debug(+ `[Backfill Events] Query ${queryId} promise resolved/rejected`,+ err?.message,);- // Don't fail the migration if truncate fails- }+ });}+ // ============================================================================+ // Validation+ // ============================================================================+async validate(args: Record<string, unknown>,attempts = 5,@@ -456,186 +685,206 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {};}- // 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),- public Bool DEFAULT false,- bookmarked Bool DEFAULT false,- is_deleted UInt8 DEFAULT 0- ) ENGINE = ReplacingMergeTree(event_ts, is_deleted)- ORDER BY (project_id, trace_id)- `,- tags: {- feature: "background-migration",- operation: "createTraceAttrsTable",- },- });+ // Validate prerequisites (sorted tables, events_backfill, backfill_chunks)+ const prereqResult = await this.validatePrerequisites();+ if (!prereqResult.valid) {+ return {+ valid: false,+ invalidReason: prereqResult.reason,+ };+ }- logger.info("[Backfill Events] trace_attrs table ready");+ logger.info("[Backfill Events] All prerequisites validated successfully");return { valid: true, invalidReason: undefined };}+ // ============================================================================+ // Main Run Loop+ // ============================================================================+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");++ // Parse config from args+ const config: MigrationState["config"] = {+ concurrency: migrationArgs.concurrency ?? DEFAULT_CONFIG.concurrency,+ pollIntervalMs:+ migrationArgs.pollIntervalMs ?? DEFAULT_CONFIG.pollIntervalMs,+ maxRetries: migrationArgs.maxRetries ?? DEFAULT_CONFIG.maxRetries,+ batchTimeoutMs:+ migrationArgs.batchTimeoutMs ?? DEFAULT_CONFIG.batchTimeoutMs,+ };logger.info(- `[Backfill Events] Starting historic event backfill with args: ${JSON.stringify({ targetChunkSize, maxModulo, batchTimeoutMs })}`,+ `[Backfill Events] Starting historic event backfill with config: ${JSON.stringify(config)}`,);// Load or initialize statelet state = await this.loadState();+ state.config = config;- // 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;- }+ // Phase 1: Load chunks from backfill_chunks table (one-time)+ if (state.phase === "init" || state.phase === "loading_chunks") {+ if (!state.chunksLoaded) {+ state.phase = "loading_chunks";+ await this.updateState(state);- // 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.todos = await this.loadChunksFromClickhouse();+ state.chunksLoaded = true;+ state.phase = "backfill";+ await this.updateState(state);}-- 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;+ // Phase 2: Recover any in-progress queries from previous run+ await this.recoverInProgressTodos(state);- if (!currentPartition) {+ // Phase 2.5: Reset failed chunks to pending if --retry-failed flag is set+ if (migrationArgs.retryFailed) {+ state = await this.loadState();+ const failedChunks = state.todos.filter((t) => t.status === "failed");+ if (failedChunks.length > 0) {logger.info(- "[Backfill Events] All partitions processed. Migration complete!",+ `[Backfill Events] Resetting ${failedChunks.length} failed chunks to pending`,);- break;+ for (const todo of state.todos) {+ if (todo.status === "failed") {+ todo.status = "pending";+ todo.error = undefined;+ todo.retryCount = 0;+ }+ }+ await this.updateState(state);}+ }- const partitionState = state.partitions[currentPartition];+ // Phase 3: Execute chunks with concurrency+ const manager = new ConcurrentQueryManager();- if (!partitionState) {- logger.error(- `[Backfill Events] Partition ${currentPartition} not found in state`,- );- break;- }+ const scheduleNext = async (): Promise<void> => {+ if (this.isAborted) return;- // 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();+ state = await this.loadState();+ const pendingTodos = state.todos.filter((t) => t.status === "pending");+ if (pendingTodos.length === 0 && manager.activeCount === 0) {+ manager.stopPolling();+ state.phase = "completed";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)`,- );+ logger.info("[Backfill Events] All chunks completed!");+ return;}- // 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`,- );+ if (manager.activeCount >= config.concurrency!) return; // At capacity- // Mark as completed and move to next partition- if (!state.completedPartitions.includes(currentPartition)) {- state.completedPartitions.push(currentPartition);- }+ const nextTodo = pendingTodos[0];+ if (!nextTodo) return;- // Find next partition to process- const allPartitions = Object.keys(state.partitions).sort().reverse();- const currentIndex = allPartitions.indexOf(currentPartition);+ // Mark as in_progress+ const todoIndex = state.todos.findIndex((t) => t.id === nextTodo.id);+ if (todoIndex === -1) return;- state.currentPartition =- currentIndex < allPartitions.length - 1- ? allPartitions[currentIndex + 1]- : null;- await this.updateState(state);- continue;- }+ state.todos[todoIndex].status = "in_progress";+ state.todos[todoIndex].queryId = generateQueryId(nextTodo.id);+ state.todos[todoIndex].startedAt = new Date().toISOString();+ state.activeQueries.push(state.todos[todoIndex].queryId!);+ await this.updateState(state);- // Process the chunk: trace_attrs -> events -> truncate+ // Fire the querytry {- // Step 1: Fill trace_attrs for this chunk- await this.processTraceAttrsChunk(- currentPartition,- nextChunk,- partitionState.modulo,- batchTimeoutMs,+ const query = this.buildQuery(state.todos[todoIndex]);+ await this.fireQuery(+ query,+ state.todos[todoIndex].queryId!,+ config.batchTimeoutMs!,+ state.todos[todoIndex].retryCount || 0,);-- // Step 2: Fill events for this chunk (joining with trace_attrs)- await this.processEventsChunk(- currentPartition,- nextChunk,- partitionState.modulo,- batchTimeoutMs,+ manager.addQuery(+ state.todos[todoIndex],+ state.todos[todoIndex].queryId!,+ );+ logger.info(+ `[Backfill Events] Started chunk ${nextTodo.id} with query ${state.todos[todoIndex].queryId}`,);+ } catch (err) {+ logger.error(+ `[Backfill Events] Failed to start query for ${nextTodo.id}`,+ err,+ );+ state.todos[todoIndex].status = "pending"; // Will retry on next scheduleNext+ state.todos[todoIndex].queryId = undefined;+ state.activeQueries = state.activeQueries.filter(+ (q) => q !== state.todos[todoIndex].queryId,+ );+ await this.updateState(state);+ }+ };- // Step 3: Truncate trace_attrs to free memory- await this.truncateTraceAttrs();+ const onComplete = async (+ todo: ChunkTodo,+ success: boolean,+ error?: string,+ ): Promise<void> => {+ state = await this.loadState();+ const todoIndex = state.todos.findIndex((t) => t.id === todo.id);+ if (todoIndex === -1) return;- // Mark chunk as completed- partitionState.chunksProcessed.push(nextChunk);- partitionState.lastUpdated = new Date().toISOString();- await this.updateState(state);+ // Remove from activeQueries+ state.activeQueries = state.activeQueries.filter(+ (q) => q !== todo.queryId,+ );+ if (success) {+ state.todos[todoIndex].status = "completed";+ state.todos[todoIndex].completedAt = new Date().toISOString();+ const completed = state.todos.filter(+ (t) => t.status === "completed",+ ).length;+ const total = state.todos.length;logger.info(- `[Backfill Events] Partition ${currentPartition}: ${partitionState.chunksProcessed.length}/${partitionState.modulo} chunks complete`,+ `[Backfill Events] Completed chunk ${todo.id} (${completed}/${total})`,);- } catch (error) {- logger.error(- `[Backfill Events] Error processing chunk ${nextChunk} for partition ${currentPartition}`,- error,- );- throw error; // Let the background migration manager handle the error+ } else {+ state.todos[todoIndex].retryCount =+ (state.todos[todoIndex].retryCount || 0) + 1;+ if (state.todos[todoIndex].retryCount >= config.maxRetries!) {+ state.todos[todoIndex].status = "failed";+ state.todos[todoIndex].error = error;+ logger.error(+ `[Backfill Events] Chunk ${todo.id} failed permanently: ${error}`,+ );+ } else {+ state.todos[todoIndex].status = "pending"; // Retry+ logger.warn(+ `[Backfill Events] Chunk ${todo.id} failed, will retry (${state.todos[todoIndex].retryCount}/${config.maxRetries}): ${error}`,+ );+ }}+ await this.updateState(state);+ };++ // Start polling and initial scheduling+ manager.startPolling(config.pollIntervalMs!, onComplete, scheduleNext);++ // Schedule initial batch up to concurrency limit+ for (let i = 0; i < config.concurrency!; i++) {+ await scheduleNext();+ }++ // Wait for all queries to complete+ while (!this.isAborted) {+ state = await this.loadState();+ const pending = state.todos.filter(+ (t) => t.status === "pending" || t.status === "in_progress",+ );+ if (pending.length === 0) break;+ await sleep(config.pollIntervalMs!);}+ manager.stopPolling();+if (this.isAborted) {logger.info(`[Backfill Events] Migration aborted. Can be resumed from current state.`,@@ -643,6 +892,14 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {return;}+ // Check for failed chunks+ const failed = state.todos.filter((t) => t.status === "failed");+ if (failed.length > 0) {+ logger.error(+ `[Backfill Events] Migration completed with ${failed.length} failed chunks`,+ );+ }+logger.info(`[Backfill Events] Finished historic event backfill in ${((Date.now() - start) / 1000 / 60).toFixed(2)} minutes`,);@@ -654,22 +911,39 @@ export default class BackfillEventsHistoric implements IBackgroundMigration {}}+// ============================================================================+// CLI Entry Point+// ============================================================================+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",- },+ concurrency: { type: "string", short: "c", default: "4" },+ pollIntervalMs: { type: "string", short: "p", default: "30000" },+ maxRetries: { type: "string", short: "r", default: "3" },+ batchTimeoutMs: { type: "string", short: "t", default: "7200000" },+ retryFailed: { type: "boolean", short: "f", default: false },},});const migration = new BackfillEventsHistoric();- await migration.validate(args.values);- await migration.run(args.values);++ const parsedArgs = {+ concurrency: parseInt(args.values.concurrency as string, 10),+ pollIntervalMs: parseInt(args.values.pollIntervalMs as string, 10),+ maxRetries: parseInt(args.values.maxRetries as string, 10),+ batchTimeoutMs: parseInt(args.values.batchTimeoutMs as string, 10),+ retryFailed: args.values.retryFailed as boolean,+ };++ const validation = await migration.validate(parsedArgs);++ if (!validation.valid) {+ logger.error(`Validation failed: ${validation.invalidReason}`);+ process.exit(1);+ }++ await migration.run(parsedArgs);}// If the script is being executed directly (not imported), run the main function