Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: V4 historic backfill background migrations (#14206)

Steffen Schmitzb1e541cc6c7e
diff --git a/packages/shared/prisma/migrations/20260701115500_add_create_root_spans_background_migration/migration.sql b/packages/shared/prisma/migrations/20260701115500_add_create_root_spans_background_migration/migration.sql
new file mode 100644
index 0000000000..eac67ba654
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260701115500_add_create_root_spans_background_migration/migration.sql
@@ -0,0 +1,14 @@
+-- M1 of the V4 self-hosted historic backfill chain.
+-- Creates virtual root spans in events_full from existing traces. Traces
+-- referenced by a dataset run item are skipped here and owned end-to-end by M4.
+--
+-- Gated by `LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL` so this row ships
+-- dormant on the final v3 release and activates when self-hosters opt in or
+-- upgrade to v4 (which defaults the flag to true).
+INSERT INTO background_migrations (id, name, script, args)
+VALUES (
+ '8e1f4a2b-5c63-4d8e-9a47-1b2f3c4d5e6f',
+ '20260701_v4_step_1_create_root_spans_from_traces',
+ 'createRootSpansFromTraces',
+ '{"envGate": "LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL"}'::jsonb
+);
diff --git a/packages/shared/prisma/migrations/20260701115501_add_rewrite_observations_to_pid_tid_sorting_background_migration/migration.sql b/packages/shared/prisma/migrations/20260701115501_add_rewrite_observations_to_pid_tid_sorting_background_migration/migration.sql
new file mode 100644
index 0000000000..fde4bef080
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260701115501_add_rewrite_observations_to_pid_tid_sorting_background_migration/migration.sql
@@ -0,0 +1,17 @@
+-- M2 of the V4 self-hosted historic backfill chain.
+-- Rewrites the live `observations` table into `observations_pid_tid_sorting`,
+-- a scratch table sorted by (project_id, trace_id, span_id) so that M3's
+-- chunked LEFT ANY JOIN against `traces` is index-aligned.
+--
+-- M2 lazily creates the scratch table inside validate() and issues
+-- `SYSTEM STOP MERGES` against it after the rewrite. The scratch table is
+-- dropped by M5 once the operator confirms the v4 path is healthy.
+--
+-- Gated by `LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL`.
+INSERT INTO background_migrations (id, name, script, args)
+VALUES (
+ '9c2d5a4f-7b8e-4f6a-a91c-3e5d7f8a2b1c',
+ '20260701_v4_step_2_rewrite_observations_to_pid_tid_sorting',
+ 'rewriteObservationsToPidTidSorting',
+ '{"envGate": "LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL"}'::jsonb
+);
diff --git a/packages/shared/prisma/migrations/20260701115502_add_backfill_events_full_from_observations_background_migration/migration.sql b/packages/shared/prisma/migrations/20260701115502_add_backfill_events_full_from_observations_background_migration/migration.sql
new file mode 100644
index 0000000000..45d7ab4f4e
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260701115502_add_backfill_events_full_from_observations_background_migration/migration.sql
@@ -0,0 +1,16 @@
+-- M3 of the V4 self-hosted historic backfill chain.
+-- Reads `observations_pid_tid_sorting` (produced by M2) LEFT ANY JOIN with the
+-- live `traces` table and writes child events into `events_full`. Trace
+-- properties are propagated lightly (name, user_id, session_id, version,
+-- release, tags, public, bookmarked); metadata is intentionally not copied to
+-- keep the join cheap on self-hoster hardware. Observations of DRI-referenced
+-- traces are skipped here and owned end-to-end by M4.
+--
+-- Gated by `LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL`.
+INSERT INTO background_migrations (id, name, script, args)
+VALUES (
+ '7a3f8d6e-2c91-4b5e-8d72-f4a5b6c7d8e9',
+ '20260701_v4_step_3_backfill_events_full_from_observations',
+ 'backfillEventsFullFromObservations',
+ '{"envGate": "LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL"}'::jsonb
+);
diff --git a/packages/shared/prisma/migrations/20260701115503_add_backfill_events_full_from_dris_background_migration/migration.sql b/packages/shared/prisma/migrations/20260701115503_add_backfill_events_full_from_dris_background_migration/migration.sql
new file mode 100644
index 0000000000..f0889f0c0b
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260701115503_add_backfill_events_full_from_dris_background_migration/migration.sql
@@ -0,0 +1,25 @@
+-- M4 of the V4 self-hosted historic backfill chain.
+-- DRI-driven recursive enrichment: walks `dataset_run_items_rmt` newest-first,
+-- finds the root span for each DRI's trace, copies the root + all descendants
+-- into `events_full` with experiment_* fields populated. Because M1 and M3 skip
+-- DRI-referenced traces, M4 owns those traces end-to-end: every remaining span
+-- of a referenced trace (the virtual trace root, siblings, ancestors) is also
+-- written, without experiment fields, so the trace tree is complete.
+--
+-- All tunables are read from `args` so a self-hoster can override them
+-- in-place via SQL on the row:
+-- - concurrency: kept for parity with the other steps; M4 is JS-batched.
+-- - batchSize: number of DRIs paginated per round (default 200).
+-- - maxDescendantsPerDri: hard cap that converts a runaway trace into an
+-- actionable error in `failedReason` rather than a silent OOM.
+-- - lookbackDays: padding applied to the DRI created_at min/max when
+-- fetching observations/traces (default 90).
+--
+-- Gated by `LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL`.
+INSERT INTO background_migrations (id, name, script, args)
+VALUES (
+ '9d4f8a12-7b35-4e6c-9f48-a2b3c4d5e6f7',
+ '20260701_v4_step_4_backfill_events_full_from_dataset_run_items',
+ 'backfillEventsFullFromDatasetRunItems',
+ '{"envGate": "LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL"}'::jsonb
+);
diff --git a/packages/shared/prisma/migrations/20260701115504_add_drop_pid_tid_sorting_tables_background_migration/migration.sql b/packages/shared/prisma/migrations/20260701115504_add_drop_pid_tid_sorting_tables_background_migration/migration.sql
new file mode 100644
index 0000000000..952b786c86
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260701115504_add_drop_pid_tid_sorting_tables_background_migration/migration.sql
@@ -0,0 +1,13 @@
+-- M5 of the V4 self-hosted historic backfill chain.
+-- Cleanup-only migration: drops `observations_pid_tid_sorting` once the operator confirms the v4 read path is healthy.
+--
+-- Gated by `LANGFUSE_BACKGROUND_MIGRATION_V4_DROP_PID_TID_SORTING_TABLES` (separate from
+-- the other gate) so users keep scratch tables for forensics until they're
+-- confident.
+INSERT INTO background_migrations (id, name, script, args)
+VALUES (
+ 'b3f1c5d8-9e47-4a26-8b3f-5c6d7e8f9a01',
+ '20260701_v4_step_5_drop_pid_tid_sorting_tables',
+ 'dropPidTidSortingTables',
+ '{"envGate": "LANGFUSE_BACKGROUND_MIGRATION_V4_DROP_PID_TID_SORTING_TABLES"}'::jsonb
+);
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index 7546eda1b5..d63dd346e0 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -32,6 +32,14 @@ import {
type NormalizedClickHouseQueryTags,
} from "../clickhouse/queryTags";
+/**
+ * Re-exported so callers can build `Array(Tuple(...))` query parameters without
+ * importing `@clickhouse/client` directly (e.g. composite `(col_a, col_b) IN`
+ * predicates). A plain JS array serializes as an `Array`; `TupleParam` is what
+ * renders each element as a `(...)` tuple, with string contents escaped.
+ */
+export { TupleParam } from "@clickhouse/client";
+
/**
* Custom error class for ClickHouse resource-related errors
*/
diff --git a/worker/src/backgroundMigrations/README.md b/worker/src/backgroundMigrations/README.md
index 5ad3e9d28d..33bfa3f3ca 100644
--- a/worker/src/backgroundMigrations/README.md
+++ b/worker/src/backgroundMigrations/README.md
@@ -38,3 +38,28 @@ If it completes, it marks the migration as done and proceeds with the next one u
If the worker is killed for any reason, another worker will pick up the migration and continue where it left off after the lock expired.
Ideally, background migrations can also be executed via the commandline, e.g. to run them locally or to test them in a staging environment.
+
+## Env-gated migrations (dormant rows)
+
+Some migrations need to ship in release N but only execute in release N+1 (or only when an operator opts in).
+The `envGate` mechanism makes a row **dormant**: it sits in `background_migrations` with `finished_at = NULL` but the manager skips it at query time until the named env var is `"true"`.
+
+The gate check lives in the `findFirst` predicate, so a dormant row does **not** head-of-line block later migrations β€” anything alphabetically after it that is either un-gated or whose gate is on will still run.
+
+### Authoring a gated migration
+
+1. **Pick a gate name** with the `LANGFUSE_BACKGROUND_MIGRATION_` prefix (the manager discovers gates by scanning the validated env for keys with this prefix).
+2. **Declare the gate in the row's `args`** in the Prisma migration SQL:
+ ```sql
+ INSERT INTO background_migrations (id, name, script, args)
+ VALUES (
+ '...',
+ '20260521120000_my_dormant_migration',
+ 'myDormantMigration',
+ '{"projectId": "...", "envGate": "LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_MY_FEATURE"}'::jsonb
+ );
+ ```
+3. **Register the env var** in `worker/src/env.ts` `EnvSchema` with `z.enum(["true", "false"]).default("false")` so it is typed, validated at boot, and dormant by default.
+
+When the env var is `"true"` the row becomes visible to the manager and runs in normal name order.
+When it is `"false"` (or absent) the row is invisible β€” no lock, no skip log, no head-of-line block.
diff --git a/worker/src/backgroundMigrations/backfillEventsFullFromDatasetRunItems.ts b/worker/src/backgroundMigrations/backfillEventsFullFromDatasetRunItems.ts
new file mode 100644
index 0000000000..ee5fef109d
--- /dev/null
+++ b/worker/src/backgroundMigrations/backfillEventsFullFromDatasetRunItems.ts
@@ -0,0 +1,842 @@
+import { IBackgroundMigration } from "./IBackgroundMigration";
+import {
+ buildClickHouseLogComment,
+ clickhouseClient,
+ convertDateToClickhouseDateTime,
+ logger,
+ queryClickhouse,
+ sleep,
+ TupleParam,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { parseArgs } from "node:util";
+import {
+ buildSpanMaps,
+ convertEnrichedSpansToEventRecords,
+ convertToEnrichedSpanWithoutExperiment,
+ enrichSpansWithExperiment,
+ findAllChildren,
+ projectScopedKey,
+ spanScopedKey,
+ type DatasetRunItem,
+ type EnrichedSpan,
+ type SpanRecord,
+ type TraceProperties,
+} from "../features/eventPropagation/handleExperimentBackfill";
+import { checkPredecessorMigrationFinalized } from "./utils/backfillBase";
+
+// Hard-coded UUID identifying the row in background_migrations. Must match
+// the Prisma migration that registers this row.
+const backgroundMigrationId = "9d4f8a12-7b35-4e6c-9f48-a2b3c4d5e6f7";
+
+// ============================================================================
+// Types
+// ============================================================================
+
+interface DriCursor {
+ projectId: string;
+ datasetId: string;
+ datasetRunId: string;
+ driId: string;
+}
+
+interface MigrationArgs {
+ pollIntervalMs?: number;
+ maxRetries?: number;
+ envGate?: string;
+ batchSize?: number;
+ maxDescendantsPerDri?: number;
+ lookbackDays?: number;
+}
+
+type ResolvedConfig = Required<Omit<MigrationArgs, "envGate">>;
+
+interface MigrationState {
+ phase: "init" | "processing" | "completed";
+ cursor: DriCursor | null;
+ processedDris: number;
+ config: ResolvedConfig;
+}
+
+const DEFAULT_CONFIG: ResolvedConfig = {
+ pollIntervalMs: 30_000,
+ maxRetries: 3,
+ batchSize: 200,
+ maxDescendantsPerDri: 50_000,
+ lookbackDays: 90,
+};
+
+// ============================================================================
+// Errors
+// ============================================================================
+
+/**
+ * Thrown when a single DRI's trace tree exceeds `maxDescendantsPerDri`.
+ *
+ * Halts the migration so the operator can either bump the cap, skip the
+ * offending DRI, or run a manual SQL fallback. The cursor in state is
+ * **not** advanced before this is thrown so a retry resumes from the same
+ * batch β€” bump the cap and re-run, or fix the cursor manually.
+ */
+class DescendantCapExceededError extends Error {
+ constructor(
+ public readonly dri: DatasetRunItem,
+ public readonly descendantCount: number,
+ public readonly cap: number,
+ ) {
+ super(
+ [
+ `DRI ${dri.id} (project=${dri.project_id}, trace=${dri.trace_id}) has`,
+ `${descendantCount} descendant spans, exceeding the cap of ${cap}.`,
+ `\n\nTo proceed, either:`,
+ ` (a) raise maxDescendantsPerDri in the background_migrations.args`,
+ ` JSONB and re-run the migration;`,
+ ` (b) advance the cursor in background_migrations.state to skip this`,
+ ` DRI β€” M1/M3 skip DRI-referenced traces, so this trace will then`,
+ ` be absent from events_full entirely; or`,
+ ` (c) handle this trace manually via SQL and then advance the cursor.`,
+ ].join(" "),
+ );
+ this.name = "DescendantCapExceededError";
+ }
+}
+
+// ============================================================================
+// Migration Class
+// ============================================================================
+
+export default class BackfillEventsFullFromDatasetRunItems implements IBackgroundMigration {
+ private isAborted = false;
+
+ // ============================================================================
+ // State Management
+ // ============================================================================
+
+ private async loadState(): Promise<MigrationState> {
+ const migration = await prisma.backgroundMigration.findUnique({
+ where: { id: backgroundMigrationId },
+ select: { state: true },
+ });
+
+ const defaultState: MigrationState = {
+ phase: "init",
+ cursor: null,
+ processedDris: 0,
+ config: { ...DEFAULT_CONFIG },
+ };
+
+ if (!migration || !migration.state) {
+ return defaultState;
+ }
+
+ const state = migration.state as Partial<MigrationState>;
+
+ return {
+ phase: state.phase ?? defaultState.phase,
+ cursor: state.cursor ?? defaultState.cursor,
+ processedDris: state.processedDris ?? defaultState.processedDris,
+ config: {
+ ...DEFAULT_CONFIG,
+ ...state.config,
+ },
+ };
+ }
+
+ private async updateState(state: MigrationState): Promise<void> {
+ await prisma.backgroundMigration.update({
+ where: { id: backgroundMigrationId },
+ data: { state: state as any },
+ });
+ }
+
+ // ============================================================================
+ // DRI Loading (cursor-paginated)
+ // ============================================================================
+
+ /**
+ * Loads the next batch of DRIs after the given cursor, ordered by the
+ * dataset_run_items_rmt PK (project_id, dataset_id, dataset_run_id, id) so
+ * the scan is index-aligned. Dedupes to one row per
+ * (project_id, trace_id, observation_id) β€” matching the live cron β€” so we
+ * don't process the same trace+observation slot twice within a batch.
+ */
+ private async loadDriBatch(
+ cursor: DriCursor | null,
+ batchSize: number,
+ ): Promise<DatasetRunItem[]> {
+ const cursorTuple: DriCursor = cursor ?? {
+ projectId: "",
+ datasetId: "",
+ datasetRunId: "",
+ driId: "",
+ };
+
+ const query = `
+ SELECT
+ dri.id,
+ dri.project_id,
+ dri.trace_id,
+ dri.observation_id,
+ dri.dataset_run_id,
+ dri.dataset_run_name,
+ dri.dataset_run_description,
+ dri.dataset_run_metadata,
+ dri.dataset_id,
+ dri.dataset_item_version,
+ dri.dataset_item_id,
+ dri.dataset_item_expected_output,
+ dri.dataset_item_metadata,
+ dri.created_at
+ FROM dataset_run_items_rmt AS dri
+ WHERE (dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.id) >
+ ({cProjectId: String}, {cDatasetId: String}, {cDatasetRunId: String}, {cDriId: String})
+ ORDER BY dri.project_id, dri.dataset_id, dri.dataset_run_id, dri.id ASC
+ LIMIT 1 BY dri.project_id, dri.trace_id, coalesce(dri.observation_id, '')
+ LIMIT {batchSize: UInt64}
+ `;
+
+ return queryClickhouse<DatasetRunItem>({
+ query,
+ params: {
+ cProjectId: cursorTuple.projectId,
+ cDatasetId: cursorTuple.datasetId,
+ cDatasetRunId: cursorTuple.datasetRunId,
+ cDriId: cursorTuple.driId,
+ batchSize,
+ },
+ clickhouseConfigs: {
+ request_timeout: 120_000,
+ },
+ tags: {
+ surface: "worker",
+ route: "background-migration.loadDriBatch",
+ },
+ });
+ }
+
+ // ============================================================================
+ // Span fetching for a DRI batch
+ // ============================================================================
+
+ /**
+ * Deduplicated `(project_id, trace_id)` pairs for the batch, as ClickHouse
+ * tuple params for composite `(project_id, trace_id) IN (...)` filters.
+ */
+ private buildTracePairs(driBatch: DatasetRunItem[]): TupleParam[] {
+ return [
+ ...new Map(
+ driBatch.map((d) => [
+ JSON.stringify([d.project_id, d.trace_id]),
+ new TupleParam([d.project_id, d.trace_id]),
+ ]),
+ ).values(),
+ ];
+ }
+
+ /**
+ * Fetches observations for the batch's traces, padded by `lookbackDays` on
+ * either side of the batch's DRI created_at window so trace timestamps that
+ * predate or postdate the DRI insert are still found.
+ */
+ private async fetchObservationsForBatch(
+ driBatch: DatasetRunItem[],
+ lookbackDays: number,
+ ): Promise<SpanRecord[]> {
+ if (driBatch.length === 0) return [];
+
+ const tracePairs = this.buildTracePairs(driBatch);
+ const { minTime, maxTime } = computeBatchTimeWindow(driBatch, lookbackDays);
+
+ const query = `
+ SELECT
+ o.project_id,
+ o.trace_id,
+ o.id AS span_id,
+ coalesce(o.parent_observation_id, concat('t-', o.trace_id)) AS parent_span_id,
+ o.start_time,
+ o.end_time,
+ o.name,
+ o.type,
+ coalesce(o.environment, '') AS environment,
+ coalesce(o.version, '') AS version,
+ '' as release,
+ coalesce(o.input, '') AS input,
+ coalesce(o.output, '') AS output,
+ o.level AS level,
+ coalesce(o.status_message, '') AS status_message,
+ o.completion_start_time AS completion_start_time,
+ coalesce(o.prompt_id, '') AS prompt_id,
+ coalesce(o.prompt_name, '') AS prompt_name,
+ o.prompt_version AS prompt_version,
+ coalesce(o.internal_model_id, '') AS model_id,
+ coalesce(o.provided_model_name, '') AS provided_model_name,
+ coalesce(o.model_parameters, '{}') AS model_parameters,
+ o.provided_usage_details AS provided_usage_details,
+ o.usage_details AS usage_details,
+ o.provided_cost_details AS provided_cost_details,
+ o.cost_details AS cost_details,
+ coalesce(o.total_cost, 0) AS total_cost,
+ o.tool_definitions,
+ o.tool_calls,
+ o.tool_call_names,
+ o.usage_pricing_tier_id,
+ o.usage_pricing_tier_name,
+ o.metadata,
+ multiIf(mapContains(o.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,
+ o.event_ts AS event_ts,
+ [] as tags,
+ false AS bookmarked,
+ false AS public,
+ '' AS trace_name,
+ '' AS user_id,
+ '' AS session_id
+ FROM observations_pid_tid_sorting o
+ WHERE (o.project_id, o.trace_id) IN {tracePairs: Array(Tuple(String, String))}
+ AND o.start_time >= {minTime: DateTime64(3)}
+ AND o.start_time <= {maxTime: DateTime64(3)}
+ ORDER BY o.event_ts DESC
+ LIMIT 1 BY o.project_id, o.trace_id, o.id
+ `;
+
+ return queryClickhouse<SpanRecord>({
+ query,
+ params: {
+ tracePairs,
+ minTime: convertDateToClickhouseDateTime(minTime),
+ maxTime: convertDateToClickhouseDateTime(maxTime),
+ },
+ clickhouseConfigs: {
+ request_timeout: 120_000,
+ },
+ tags: {
+ surface: "worker",
+ route: "background-migration.fetchObservationsForBatch",
+ },
+ });
+ }
+
+ /**
+ * Fetches traces for the batch, padded by `lookbackDays`.
+ */
+ private async fetchTracesForBatch(
+ driBatch: DatasetRunItem[],
+ lookbackDays: number,
+ ): Promise<SpanRecord[]> {
+ if (driBatch.length === 0) return [];
+
+ const tracePairs = this.buildTracePairs(driBatch);
+ const { minTime, maxTime } = computeBatchTimeWindow(driBatch, lookbackDays);
+
+ const query = `
+ SELECT
+ t.project_id,
+ t.id AS trace_id,
+ concat('t-', t.id) AS span_id,
+ '' AS parent_span_id,
+ t.timestamp AS start_time,
+ '' AS end_time,
+ t.name AS name,
+ 'SPAN' AS type,
+ coalesce(t.environment, '') AS environment,
+ coalesce(t.version, '') AS version,
+ coalesce(t.release, '') AS release,
+ coalesce(t.input, '') AS input,
+ coalesce(t.output, '') AS output,
+ '' AS level,
+ '' AS status_message,
+ '' AS completion_start_time,
+ '' AS prompt_id,
+ '' AS prompt_name,
+ '' AS prompt_version,
+ '' AS model_id,
+ '' AS provided_model_name,
+ '' AS model_parameters,
+ map() AS provided_usage_details,
+ map() AS usage_details,
+ map() AS provided_cost_details,
+ map() AS cost_details,
+ 0 AS total_cost,
+ map() AS tool_definitions,
+ [] AS tool_calls,
+ [] AS tool_call_names,
+ t.metadata,
+ multiIf(mapContains(t.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,
+ t.tags,
+ t.bookmarked,
+ t.public,
+ t.name AS trace_name,
+ coalesce(t.user_id, '') AS user_id,
+ coalesce(t.session_id, '') AS session_id,
+ t.event_ts AS event_ts
+ FROM traces t
+ WHERE (t.project_id, t.id) IN {tracePairs: Array(Tuple(String, String))}
+ AND t.timestamp >= {minTime: DateTime64(3)}
+ AND t.timestamp <= {maxTime: DateTime64(3)}
+ ORDER BY t.event_ts DESC
+ LIMIT 1 BY t.project_id, t.id
+ `;
+
+ return queryClickhouse<SpanRecord>({
+ query,
+ params: {
+ tracePairs,
+ minTime: convertDateToClickhouseDateTime(minTime),
+ maxTime: convertDateToClickhouseDateTime(maxTime),
+ },
+ clickhouseConfigs: {
+ request_timeout: 120_000,
+ },
+ tags: {
+ surface: "worker",
+ route: "background-migration.fetchTracesForBatch",
+ },
+ });
+ }
+
+ // ============================================================================
+ // Batch processing
+ // ============================================================================
+
+ /**
+ * Inserts enriched spans into events_full synchronously. The migration
+ * deliberately bypasses the shared ClickhouseWriter queue.
+ * An awaited insert keeps the invariant that the cursor only
+ * moves past durably written data. Transient insert failures propagate to
+ * the batch retry loop in run(); re-inserting a batch is safe because
+ * events_full is a ReplacingMergeTree.
+ */
+ private async insertEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {
+ if (spans.length === 0) return;
+
+ await clickhouseClient().insert({
+ table: "events_full",
+ format: "JSONEachRow",
+ // plainEventTsFromSource: plain (leftover) spans keep their source
+ // event_ts so an enriched copy of the same span from another batch always
+ // wins; enriched spans still use now().
+ values: convertEnrichedSpansToEventRecords(spans, {
+ plainEventTsFromSource: true,
+ }),
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: "background-migration.backfillEventsFullFromDatasetRunItems",
+ }),
+ },
+ });
+ }
+
+ /**
+ * Enriches one DRI batch and inserts the resulting EnrichedSpans into
+ * events_full. Throws DescendantCapExceededError if any DRI's trace
+ * exceeds the cap.
+ */
+ private async processBatch(
+ driBatch: DatasetRunItem[],
+ config: ResolvedConfig,
+ ): Promise<{ enriched: number; skipped: number }> {
+ const [observations, traces] = await Promise.all([
+ this.fetchObservationsForBatch(driBatch, config.lookbackDays),
+ this.fetchTracesForBatch(driBatch, config.lookbackDays),
+ ]);
+
+ logger.info(
+ `[Backfill Events DRIs] Fetched ${observations.length} observations and ${traces.length} traces for ${driBatch.length} DRIs`,
+ );
+
+ const allSpans: SpanRecord[] = [...observations, ...traces];
+ const { spanMap, childMap } = buildSpanMaps(allSpans);
+
+ const tracePropertiesMap = new Map<string, TraceProperties>();
+ for (const trace of traces) {
+ tracePropertiesMap.set(
+ projectScopedKey(trace.project_id, trace.trace_id),
+ {
+ name: trace.name,
+ userId: trace.user_id,
+ sessionId: trace.session_id,
+ version: trace.version,
+ release: trace.release,
+ tags: trace.tags,
+ bookmarked: trace.bookmarked,
+ public: trace.public,
+ },
+ );
+ }
+
+ const allEnrichedSpans: EnrichedSpan[] = [];
+ // Span keys already emitted as part of a DRI subtree, so the leftover pass
+ // below doesn't write a plain duplicate of them.
+ const enrichedSpanKeys = new Set<string>();
+ let skipped = 0;
+
+ for (const dri of driBatch) {
+ const rootSpanId = dri.observation_id || `t-${dri.trace_id}`;
+ const rootSpanKey = spanScopedKey(
+ dri.project_id,
+ dri.trace_id,
+ rootSpanId,
+ );
+ const rootSpan = spanMap.get(rootSpanKey);
+
+ if (!rootSpan) {
+ logger.warn(
+ `[Backfill Events DRIs] Root span ${rootSpanId} not found for DRI ${dri.id} (project=${dri.project_id}, trace=${dri.trace_id}); skipping`,
+ );
+ skipped++;
+ continue;
+ }
+
+ const childSpans = findAllChildren(rootSpanKey, childMap);
+ if (childSpans.length > config.maxDescendantsPerDri) {
+ // Persist the DRIs enriched so far before halting, so an operator
+ // who advances the cursor past the offending DRI does not lose the
+ // earlier DRIs of this batch. (The structural leftover spans for those
+ // traces are only written once the batch completes normally on resume.)
+ await this.insertEnrichedSpans(allEnrichedSpans);
+
+ throw new DescendantCapExceededError(
+ dri,
+ childSpans.length,
+ config.maxDescendantsPerDri,
+ );
+ }
+
+ const traceProperties = tracePropertiesMap.get(
+ projectScopedKey(dri.project_id, dri.trace_id),
+ );
+ const enrichedSpans = enrichSpansWithExperiment(
+ rootSpan,
+ childSpans,
+ dri,
+ traceProperties,
+ );
+ allEnrichedSpans.push(...enrichedSpans);
+
+ enrichedSpanKeys.add(rootSpanKey);
+ for (const child of childSpans) {
+ enrichedSpanKeys.add(
+ spanScopedKey(child.project_id, child.trace_id, child.span_id),
+ );
+ }
+ }
+
+ // Leftover pass: M4 owns every DRI-referenced trace end-to-end (M1 and M3
+ // skip referenced traces), so any fetched span that isn't part of an
+ // enriched DRI subtree β€” the virtual trace root for observation-level DRIs,
+ // plus sibling/ancestor spans β€” is materialized here without experiment
+ // fields. These keep their source event_ts (see insertEnrichedSpans), so an
+ // enriched copy of the same span produced by a DRI in another batch always
+ // wins the events_full merge/argMax.
+ let plainLeftovers = 0;
+ for (const span of allSpans) {
+ const spanKey = spanScopedKey(
+ span.project_id,
+ span.trace_id,
+ span.span_id,
+ );
+ if (enrichedSpanKeys.has(spanKey)) continue;
+ const traceProperties = tracePropertiesMap.get(
+ projectScopedKey(span.project_id, span.trace_id),
+ );
+ allEnrichedSpans.push(
+ convertToEnrichedSpanWithoutExperiment(span, traceProperties),
+ );
+ plainLeftovers++;
+ }
+
+ await this.insertEnrichedSpans(allEnrichedSpans);
+
+ logger.info(
+ `[Backfill Events DRIs] Wrote ${allEnrichedSpans.length} spans (${plainLeftovers} plain leftovers) for ${driBatch.length} DRIs`,
+ );
+
+ return { enriched: allEnrichedSpans.length, skipped };
+ }
+
+ // ============================================================================
+ // Validation
+ // ============================================================================
+
+ async validate(
+ args: Record<string, unknown>,
+ attempts = 5,
+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {
+ const predecessor = await checkPredecessorMigrationFinalized(
+ "7a3f8d6e-2c91-4b5e-8d72-f4a5b6c7d8e9",
+ "20260701_v4_step_3_backfill_events_full_from_observations",
+ );
+ if (!predecessor.valid) {
+ return predecessor;
+ }
+
+ const tables = await clickhouseClient().query({ query: "SHOW TABLES" });
+ const tableNames = (await tables.json()).data as { name: string }[];
+
+ const requiredTables = [
+ "dataset_run_items_rmt",
+ "observations_pid_tid_sorting",
+ "traces",
+ "events_full",
+ "events_core",
+ ];
+ for (const table of requiredTables) {
+ if (!tableNames.some((r) => r.name === table)) {
+ if (attempts > 0) {
+ logger.info(
+ `[Backfill Events DRIs] ${table} 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 ${table} table does not exist`,
+ };
+ }
+ }
+
+ logger.info(
+ "[Backfill Events DRIs] 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 config: ResolvedConfig = {
+ pollIntervalMs:
+ migrationArgs.pollIntervalMs ?? DEFAULT_CONFIG.pollIntervalMs,
+ maxRetries: migrationArgs.maxRetries ?? DEFAULT_CONFIG.maxRetries,
+ batchSize: migrationArgs.batchSize ?? DEFAULT_CONFIG.batchSize,
+ maxDescendantsPerDri:
+ migrationArgs.maxDescendantsPerDri ??
+ DEFAULT_CONFIG.maxDescendantsPerDri,
+ lookbackDays: migrationArgs.lookbackDays ?? DEFAULT_CONFIG.lookbackDays,
+ };
+
+ logger.info(
+ `[Backfill Events DRIs] Starting events_full backfill from dataset_run_items_rmt with config: ${JSON.stringify(config)}`,
+ );
+
+ let state = await this.loadState();
+ state.config = config;
+
+ if (state.phase === "init") {
+ state.phase = "processing";
+ }
+ await this.updateState(state);
+
+ if (state.phase === "completed") {
+ logger.info(
+ `[Backfill Events DRIs] Migration already marked completed (processed ${state.processedDris} DRIs); nothing to do`,
+ );
+ return;
+ }
+
+ let totalEnriched = 0;
+ let totalSkipped = 0;
+ let consecutiveBatchFailures = 0;
+
+ while (!this.isAborted) {
+ let driBatch: DatasetRunItem[];
+ try {
+ driBatch = await this.loadDriBatch(state.cursor, config.batchSize);
+ } catch (err) {
+ consecutiveBatchFailures++;
+ logger.error(
+ `[Backfill Events DRIs] Failed to load DRI batch (failure ${consecutiveBatchFailures}/${config.maxRetries})`,
+ err,
+ );
+ if (consecutiveBatchFailures >= config.maxRetries) {
+ throw err;
+ }
+ await sleep(config.pollIntervalMs);
+ continue;
+ }
+
+ if (driBatch.length === 0) {
+ state.phase = "completed";
+ await this.updateState(state);
+ logger.info(
+ `[Backfill Events DRIs] No more DRIs to process; processed ${state.processedDris} DRIs in total`,
+ );
+ break;
+ }
+
+ logger.info(
+ `[Backfill Events DRIs] Processing batch of ${driBatch.length} DRIs (cursor: ${
+ state.cursor
+ ? `${state.cursor.projectId}/${state.cursor.datasetId}/${state.cursor.datasetRunId}/${state.cursor.driId}`
+ : "<start>"
+ })`,
+ );
+
+ try {
+ const { enriched, skipped } = await this.processBatch(driBatch, config);
+ totalEnriched += enriched;
+ totalSkipped += skipped;
+ consecutiveBatchFailures = 0;
+ } catch (err) {
+ if (err instanceof DescendantCapExceededError) {
+ // Hard stop. Log and rethrow so the manager records failedAt and
+ // the operator can act on the structured message.
+ logger.error(
+ `[Backfill Events DRIs] Descendant cap exceeded β€” halting`,
+ err,
+ );
+ throw err;
+ }
+ consecutiveBatchFailures++;
+ logger.error(
+ `[Backfill Events DRIs] Failed to process batch (failure ${consecutiveBatchFailures}/${config.maxRetries})`,
+ err,
+ );
+ if (consecutiveBatchFailures >= config.maxRetries) {
+ throw err;
+ }
+ await sleep(config.pollIntervalMs);
+ continue;
+ }
+
+ // Advance cursor to the last DRI's PK so a resume picks up after it.
+ // The batch's writes were awaited in processBatch, so the cursor never
+ // moves past data that is not durably in ClickHouse.
+ const last = driBatch[driBatch.length - 1];
+ state.cursor = {
+ projectId: last.project_id,
+ datasetId: last.dataset_id,
+ datasetRunId: last.dataset_run_id,
+ driId: last.id,
+ };
+ state.processedDris += driBatch.length;
+ await this.updateState(state);
+
+ // Brief pause between batches so we don't hot-loop the DRI table.
+ await sleep(Math.min(config.pollIntervalMs, 5_000));
+ }
+
+ if (this.isAborted) {
+ logger.info(
+ "[Backfill Events DRIs] Migration aborted. Can be resumed from current state.",
+ );
+ return;
+ }
+
+ logger.info(
+ `[Backfill Events DRIs] Finished events_full backfill in ${(
+ (Date.now() - start) /
+ 1000 /
+ 60
+ ).toFixed(
+ 2,
+ )} minutes (enriched=${totalEnriched}, skipped=${totalSkipped})`,
+ );
+ }
+
+ async abort(): Promise<void> {
+ logger.info("[Backfill Events DRIs] Aborting migration");
+ this.isAborted = true;
+ }
+}
+
+// ============================================================================
+// Helpers
+// ============================================================================
+
+function computeBatchTimeWindow(
+ driBatch: DatasetRunItem[],
+ lookbackDays: number,
+): { minTime: Date; maxTime: Date } {
+ const dayMs = 24 * 60 * 60 * 1000;
+ const timestamps = driBatch.map((d) => new Date(d.created_at).getTime());
+ const minTs = Math.min(...timestamps);
+ const maxTs = Math.max(...timestamps);
+ return {
+ minTime: new Date(minTs - lookbackDays * dayMs),
+ maxTime: new Date(maxTs + lookbackDays * dayMs),
+ };
+}
+
+// ============================================================================
+// CLI Entry Point
+// ============================================================================
+
+async function main() {
+ process.on("unhandledRejection", (reason) => {
+ logger.error(
+ "[Backfill Events DRIs] Unhandled promise rejection - process will exit",
+ {
+ reason: reason instanceof Error ? reason.message : String(reason),
+ stack: reason instanceof Error ? reason.stack : undefined,
+ },
+ );
+ process.exit(1);
+ });
+
+ process.on("uncaughtException", (error) => {
+ logger.error(
+ "[Backfill Events DRIs] Uncaught exception - process will exit",
+ error,
+ );
+ process.exit(1);
+ });
+
+ const args = parseArgs({
+ options: {
+ pollIntervalMs: { type: "string", short: "p", default: "30000" },
+ maxRetries: { type: "string", short: "r", default: "3" },
+ batchSize: { type: "string", short: "b", default: "200" },
+ maxDescendantsPerDri: {
+ type: "string",
+ short: "d",
+ default: "50000",
+ },
+ lookbackDays: { type: "string", short: "l", default: "90" },
+ },
+ });
+
+ const migration = new BackfillEventsFullFromDatasetRunItems();
+
+ const parsedArgs = {
+ pollIntervalMs: parseInt(args.values.pollIntervalMs as string, 10),
+ maxRetries: parseInt(args.values.maxRetries as string, 10),
+ batchSize: parseInt(args.values.batchSize as string, 10),
+ maxDescendantsPerDri: parseInt(
+ args.values.maxDescendantsPerDri as string,
+ 10,
+ ),
+ lookbackDays: parseInt(args.values.lookbackDays as string, 10),
+ };
+
+ const validation = await migration.validate(parsedArgs);
+
+ if (!validation.valid) {
+ logger.error(`Validation failed: ${validation.invalidReason}`);
+ process.exit(1);
+ }
+
+ await migration.run(parsedArgs);
+}
+
+if (require.main === module) {
+ main()
+ .then(() => {
+ process.exit(0);
+ })
+ .catch((error) => {
+ logger.error(`Migration execution failed: ${error}`, error);
+ process.exit(1);
+ });
+}
diff --git a/worker/src/backgroundMigrations/backfillEventsFullFromObservations.ts b/worker/src/backgroundMigrations/backfillEventsFullFromObservations.ts
new file mode 100644
index 0000000000..808c68d4b4
--- /dev/null
+++ b/worker/src/backgroundMigrations/backfillEventsFullFromObservations.ts
@@ -0,0 +1,465 @@
+import { logger, queryClickhouse, sleep } from "@langfuse/shared/src/server";
+import { env } from "../env";
+import {
+ BaseChunkTodo,
+ ChunkedBackfillState,
+ ChunkedClickhouseBackfillMigration,
+ ResolvedChunkedBackfillConfig,
+ assertSafePartition,
+ detectTableEngine,
+ runBackfillMigrationCli,
+} from "./utils/backfillBase";
+
+// Hard-coded UUID identifying the row in background_migrations. Must match
+// the Prisma migration that registers this row.
+const backgroundMigrationId = "7a3f8d6e-2c91-4b5e-8d72-f4a5b6c7d8e9";
+
+const LOG_PREFIX = "[Backfill Events Observations]";
+
+interface PartChunkTodo extends BaseChunkTodo {
+ partId: string;
+}
+
+/**
+ * V4 chain step 3: backfills `events_full` from the
+ * `observations_pid_tid_sorting` scratch table (populated by M2), one
+ * ClickHouse part per chunk, joining live `traces` for property propagation.
+ */
+export default class BackfillEventsFullFromObservations extends ChunkedClickhouseBackfillMigration<PartChunkTodo> {
+ protected readonly migrationId = backgroundMigrationId;
+ protected readonly logPrefix = LOG_PREFIX;
+ protected readonly requiredTables = [
+ "observations_pid_tid_sorting",
+ "traces",
+ "events_full",
+ "events_core",
+ "dataset_run_items_rmt",
+ ];
+ protected readonly predecessor = {
+ id: "9c2d5a4f-7b8e-4f6a-a91c-3e5d7f8a2b1c",
+ name: "20260701_v4_step_2_rewrite_observations_to_pid_tid_sorting",
+ };
+
+ // ==========================================================================
+ // Validation
+ // ==========================================================================
+
+ /**
+ * On top of the base table/predecessor checks, verify the scratch table's
+ * part layout is identical across every replica before we start reading
+ * `system.parts` and issuing `_part`-targeted INSERTs.
+ */
+ async validate(
+ args: Record<string, unknown>,
+ attempts = 5,
+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {
+ const base = await super.validate(args, attempts);
+ if (!base.valid) return base;
+ return this.assertReplicasConverged(attempts);
+ }
+
+ /**
+ * Polls `system.replicas` across all replicas (via `clusterAllReplicas`)
+ * until every known replica is online, writable, and reports a drained
+ * replication queue β€” which, with merges frozen and no new writes, implies
+ * identical active part sets. Uses `system.replicas` (one row per replica
+ * regardless of part count) rather than diffing `system.parts` directly,
+ * which would be blind to a replica that has simply not fetched any parts
+ * yet. No-op unless the scratch table is a replicated engine: single-node
+ * has one authoritative view and Cloud/SharedMergeTree keeps part metadata
+ * centrally consistent.
+ */
+ private async assertReplicasConverged(
+ attempts: number,
+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {
+ const engine = await detectTableEngine("observations_pid_tid_sorting");
+ if (!engine.startsWith("Replicated")) {
+ logger.info(
+ `${this.logPrefix} Skipping cross-replica consistency check (engine=${engine || "unknown"} is not replicated)`,
+ );
+ return { valid: true, invalidReason: undefined };
+ }
+
+ const cluster = env.CLICKHOUSE_CLUSTER_NAME;
+ let lastSummary = "no replicas reported";
+
+ for (let attempt = 0; attempt <= attempts; attempt++) {
+ const status = await this.readReplicaConvergence(cluster);
+ if (status.converged) {
+ logger.info(
+ `${this.logPrefix} Cross-replica consistency check passed (${status.summary})`,
+ );
+ return { valid: true, invalidReason: undefined };
+ }
+ lastSummary = status.summary;
+ if (attempt < attempts) {
+ logger.info(
+ `${this.logPrefix} Replicas of observations_pid_tid_sorting not yet converged (${status.summary}). Retrying in 10s...`,
+ );
+ await sleep(10_000);
+ }
+ }
+
+ return {
+ valid: false,
+ invalidReason:
+ `observations_pid_tid_sorting replicas have not converged (${lastSummary}). ` +
+ `M2 freezes merges and syncs all replicas on success, so this indicates a replica joined or ` +
+ `recovered after M2, or M3 resumed after a topology change. Once replication settles (or after ` +
+ `running SYSTEM SYNC REPLICA ON CLUSTER ${cluster} observations_pid_tid_sorting STRICT), clear ` +
+ `failedAt and re-run.`,
+ };
+ }
+
+ /**
+ * Reads one convergence snapshot from `system.replicas` across the cluster.
+ * Every known replica must respond, be online and writable, and report a
+ * fully drained replication queue (no pending fetches/merges). Unreachable
+ * replicas are skipped by `skip_unavailable_shards` and then surface as
+ * `responding < expected`, so they are treated as not-converged rather than
+ * erroring the whole check.
+ */
+ private async readReplicaConvergence(
+ cluster: string,
+ ): Promise<{ converged: boolean; summary: string }> {
+ const rows = await queryClickhouse<{
+ responding_replicas: string;
+ expected_replicas: string;
+ min_active_replicas: string;
+ total_queue_size: string;
+ total_future_parts: string;
+ expired_replicas: string;
+ readonly_replicas: string;
+ }>({
+ query: `
+ SELECT
+ count() AS responding_replicas,
+ max(total_replicas) AS expected_replicas,
+ min(active_replicas) AS min_active_replicas,
+ sum(queue_size) AS total_queue_size,
+ sum(future_parts) AS total_future_parts,
+ countIf(is_session_expired) AS expired_replicas,
+ countIf(is_readonly) AS readonly_replicas
+ FROM clusterAllReplicas('${cluster}', 'system.replicas')
+ WHERE database = currentDatabase()
+ AND table = 'observations_pid_tid_sorting'
+ `,
+ clickhouseSettings: {
+ skip_unavailable_shards: 1,
+ },
+ tags: {
+ surface: "worker",
+ route: "background-migration.assertReplicasConverged",
+ },
+ });
+
+ const r = rows[0];
+ const responding = parseInt(r?.responding_replicas ?? "0", 10);
+ const expected = parseInt(r?.expected_replicas ?? "0", 10);
+ const minActive = parseInt(r?.min_active_replicas ?? "0", 10);
+ const queue = parseInt(r?.total_queue_size ?? "0", 10);
+ const future = parseInt(r?.total_future_parts ?? "0", 10);
+ const expired = parseInt(r?.expired_replicas ?? "0", 10);
+ const readonly = parseInt(r?.readonly_replicas ?? "0", 10);
+
+ const summary =
+ `responding=${responding}, expected=${expected}, minActive=${minActive}, ` +
+ `queueSize=${queue}, futureParts=${future}, expired=${expired}, readonly=${readonly}`;
+
+ const converged =
+ responding > 0 &&
+ responding >= expected &&
+ minActive >= expected &&
+ queue === 0 &&
+ future === 0 &&
+ expired === 0 &&
+ readonly === 0;
+
+ return { converged, summary };
+ }
+
+ // ==========================================================================
+ // Part discovery
+ // ==========================================================================
+
+ /**
+ * Enumerates active parts of `observations_pid_tid_sorting` from
+ * `system.parts`, newest partition first. One todo per part keeps each
+ * INSERT bounded to a single ClickHouse part (single-digit GBs in most
+ * cases, capped well below an entire monthly partition), which is the only
+ * granularity that's safe to assume self-hoster hardware can chew through
+ * without OOM or memory-limit failures.
+ *
+ * Partition restriction (`--partitions`) is not supported here β€” chunks are
+ * parts, not partitions, and a restricted run would silently leave the
+ * remaining parts unprocessed.
+ *
+ * Excludes meta partitions that aren't yyyymm data ranges:
+ * - `all` β€” appears on tables without a PARTITION BY clause.
+ * - `patch-%` β€” used by patch tables for ad hoc corrections.
+ */
+ protected async enumerateChunks(
+ _config: ResolvedChunkedBackfillConfig,
+ ): Promise<PartChunkTodo[]> {
+ logger.info(`${this.logPrefix} Discovering parts from system.parts`);
+
+ const parts = await queryClickhouse<{
+ partition_id: string;
+ name: string;
+ }>({
+ query: `
+ SELECT partition_id, name
+ FROM system.parts
+ WHERE table = 'observations_pid_tid_sorting'
+ AND database = currentDatabase()
+ AND active = 1
+ AND partition_id NOT LIKE 'patch-%'
+ AND partition_id != 'all'
+ ORDER BY partition_id DESC, name
+ `,
+ tags: {
+ surface: "worker",
+ route: "background-migration.loadPartsFromClickhouse",
+ },
+ });
+
+ logger.info(
+ `${this.logPrefix} Loaded ${parts.length} parts from system.parts`,
+ );
+
+ return parts.map((part) => ({
+ id: part.name,
+ partId: part.name,
+ partition: part.partition_id,
+ status: "pending" as const,
+ }));
+ }
+
+ private async getActivePartIds(): Promise<Set<string>> {
+ const parts = await queryClickhouse<{ name: string }>({
+ query: `
+ SELECT name
+ FROM system.parts
+ WHERE table = 'observations_pid_tid_sorting'
+ AND database = currentDatabase()
+ AND active = 1
+ `,
+ tags: {
+ surface: "worker",
+ route: "background-migration.getActivePartIds",
+ },
+ });
+ return new Set(parts.map((p) => p.name));
+ }
+
+ // ==========================================================================
+ // Query building
+ // ==========================================================================
+
+ /**
+ * Builds the per-part INSERT into events_full.
+ *
+ * To keep the join scan small, we bound `traces` by a `timestamp` window aligned with the observation
+ * partition's month. This may produce some observation on the month boundary that do not have full
+ * propagation. Light trace property propagation only β€”
+ * `trace.metadata` is intentionally excluded; the observation's metadata is
+ * used as-is.
+ */
+ protected buildChunkQuery(todo: PartChunkTodo): {
+ query: string;
+ params: Record<string, unknown>;
+ } {
+ assertSafePartition(todo.partition);
+
+ // The traces subquery dedupes to the latest row per (project_id, id):
+ // traces is a ReplacingMergeTree, so unmerged duplicate versions co-exist
+ // between background merges and ANY-join strictness would pick an
+ // arbitrary one.
+ //
+ // `bookmarked` is only propagated to root spans (observations without a
+ // parent); child spans always get false.
+ const query = `
+ INSERT INTO events_full (
+ project_id, trace_id, span_id, parent_span_id, start_time, end_time,
+ name, type, environment, version, release, tags, public, bookmarked,
+ trace_name, 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, tool_definitions, tool_calls, tool_call_names,
+ usage_pricing_tier_id, usage_pricing_tier_name,
+ input, output,
+ metadata_names, metadata_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 AND (o.parent_observation_id IS NULL OR o.parent_observation_id = '') AS bookmarked,
+ coalesce(t.name, '') AS trace_name,
+ 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,
+ o.tool_definitions,
+ o.tool_calls,
+ o.tool_call_names,
+ o.usage_pricing_tier_id,
+ o.usage_pricing_tier_name,
+ coalesce(o.input, '') AS input,
+ coalesce(o.output, '') AS output,
+ mapKeys(o.metadata) AS metadata_names,
+ mapValues(o.metadata) AS metadata_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 (
+ SELECT project_id, id, version, release, tags, public, bookmarked, name, user_id, session_id
+ FROM traces t
+ WHERE t._partition_id = {partition: String}
+ ORDER BY event_ts DESC
+ LIMIT 1 BY project_id, id
+ ) t
+ ON o.project_id = t.project_id AND o.trace_id = t.id
+ WHERE o._partition_id = {partition: String}
+ AND o._part = {partId: String}
+ -- Skip observations of DRI-referenced traces: M4 owns those traces
+ -- end-to-end (every observation, enriched). Keeps ownership disjoint
+ -- with M1/M4. Relies on the same per-project co-location as the join.
+ AND (o.project_id, o.trace_id) NOT IN (
+ SELECT project_id, trace_id FROM dataset_run_items_rmt
+ )
+ SETTINGS
+ join_algorithm = 'full_sorting_merge',
+ type_json_skip_duplicated_paths = 1
+ `;
+
+ return {
+ query,
+ params: {
+ partition: todo.partition,
+ partId: todo.partId,
+ },
+ };
+ }
+
+ // ==========================================================================
+ // Part-integrity verification
+ // ==========================================================================
+
+ /**
+ * Confirms a part is still active after its INSERT completed. ClickHouse
+ * merges parts in the background; if our source part disappeared between
+ * listing and processing, the INSERT may have read 0 rows and the merged
+ * successor part is not in this run's todo list. Returning the error halts
+ * the migration so the operator can clear `state.chunksLoaded` (or wipe
+ * state) and re-run so the merged successor gets enumerated and processed.
+ */
+ protected async verifyCompletedChunk(
+ todo: PartChunkTodo,
+ ): Promise<string | null> {
+ const result = await queryClickhouse<{ count: string }>({
+ query: `
+ SELECT count() AS count
+ FROM system.parts
+ WHERE table = 'observations_pid_tid_sorting'
+ AND database = currentDatabase()
+ AND name = {partId: String}
+ AND active = 1
+ `,
+ params: { partId: todo.partId },
+ tags: {
+ surface: "worker",
+ route: "background-migration.verifyPartStillActive",
+ },
+ });
+ const partStillActive =
+ result.length > 0 && parseInt(result[0].count, 10) > 0;
+ if (partStillActive) return null;
+
+ return (
+ `Part ${todo.partId} no longer active after processing β€” its rows are in a ` +
+ `merged successor part that is not in this run's todo list. Clear failedAt ` +
+ `and re-run with state.chunksLoaded=false to enumerate the merged successor.`
+ );
+ }
+
+ /**
+ * Final verification: confirm every completed part is still active. If a
+ * part merged into a larger successor that wasn't in our todo list, the
+ * successor's rows were never inserted β€” surface this so the operator
+ * knows to clear state.chunksLoaded and re-run.
+ */
+ protected async onBackfillSucceeded(
+ state: ChunkedBackfillState<PartChunkTodo>,
+ ): Promise<void> {
+ const completedTodos = state.todos.filter((t) => t.status === "completed");
+ if (completedTodos.length === 0) return;
+
+ logger.info(
+ `${this.logPrefix} Running final verification for ${completedTodos.length} completed parts...`,
+ );
+ const activePartIds = await this.getActivePartIds();
+ const missingParts = completedTodos.filter(
+ (t) => !activePartIds.has(t.partId),
+ );
+ if (missingParts.length > 0) {
+ const sample = missingParts
+ .slice(0, 10)
+ .map((p) => p.partId)
+ .join(", ");
+ const tail =
+ missingParts.length > 10
+ ? ` (and ${missingParts.length - 10} more)`
+ : "";
+ logger.error(
+ `${this.logPrefix} CRITICAL: ${missingParts.length} processed parts are no longer active. ` +
+ `Their merged successors are not in this run's todo list. ` +
+ `Re-run with state.chunksLoaded=false to enumerate and process them. Sample: ${sample}${tail}`,
+ );
+ throw new Error(
+ `Migration completed but ${missingParts.length} parts are no longer active β€” re-run with state.chunksLoaded=false`,
+ );
+ }
+ logger.info(
+ `${this.logPrefix} Final verification passed β€” all ${completedTodos.length} parts still active`,
+ );
+ }
+}
+
+// ============================================================================
+// CLI Entry Point
+// ============================================================================
+
+if (require.main === module) {
+ runBackfillMigrationCli(() => new BackfillEventsFullFromObservations(), {
+ logPrefix: LOG_PREFIX,
+ includePartitions: false,
+ });
+}
diff --git a/worker/src/backgroundMigrations/backgroundMigrationManager.ts b/worker/src/backgroundMigrations/backgroundMigrationManager.ts
index 7a8812d498..9602af7d79 100644
--- a/worker/src/backgroundMigrations/backgroundMigrationManager.ts
+++ b/worker/src/backgroundMigrations/backgroundMigrationManager.ts
@@ -2,6 +2,9 @@ import { randomUUID } from "crypto";
import { IBackgroundMigration } from "./IBackgroundMigration";
import { prisma, Prisma } from "@langfuse/shared/src/db";
import { instrumentAsync, logger } from "@langfuse/shared/src/server";
+import { env } from "../env";
+
+const ENV_GATE_PREFIX = "LANGFUSE_BACKGROUND_MIGRATION_";
export class BackgroundMigrationManager {
private static workerId = randomUUID();
@@ -37,16 +40,37 @@ export class BackgroundMigrationManager {
public static async run(): Promise<void> {
await instrumentAsync({ name: "background-migration-run" }, async () => {
+ // A migration row may declare `args.envGate = "<ENV_VAR>"` to remain dormant
+ // until the operator sets that env var to "true" (e.g. ship dormant on v3,
+ // activate on v4). We push the gate check into the findFirst predicate so
+ // dormant rows never get picked β€” otherwise the first dormant row in name
+ // order would head-of-line block every unrelated later migration.
+ //
+ // Gate names share the LANGFUSE_BACKGROUND_MIGRATION_ prefix so we can
+ // discover them via the validated env without scanning all of process.env.
+ const activeGates = Object.entries(env)
+ .filter(
+ ([key, value]) => key.startsWith(ENV_GATE_PREFIX) && value === "true",
+ )
+ .map(([key]) => key);
+
let migrationToRun = true;
while (migrationToRun) {
await prisma.$transaction(
async (tx) => {
- // Read background migrations from database
+ // Read background migrations from database, ignoring any row whose
+ // envGate is set to an env var that is not currently "true".
const migration = await tx.backgroundMigration.findFirst({
where: {
finishedAt: null,
failedAt: null,
+ OR: [
+ { args: { path: ["envGate"], equals: Prisma.AnyNull } },
+ ...activeGates.map((gate) => ({
+ args: { path: ["envGate"], equals: gate },
+ })),
+ ],
},
orderBy: { name: "asc" },
});
@@ -103,15 +127,18 @@ export class BackgroundMigrationManager {
// Initiate heartbeats every couple seconds
await BackgroundMigrationManager.heartBeat();
- const { migration, args } = BackgroundMigrationManager.activeMigration;
+ // Capture a local reference so the catch handler stays type-safe even if
+ // close() concurrently nulls activeMigration during shutdown.
+ const active = BackgroundMigrationManager.activeMigration;
+ const { migration, args } = active;
const { valid, invalidReason } = await migration.validate(args);
if (!valid) {
logger.error(
- `[Background Migration] Validation failed for background migration ${BackgroundMigrationManager.activeMigration.name}: ${invalidReason}`,
+ `[Background Migration] Validation failed for background migration ${active.name}: ${invalidReason}`,
);
await prisma.backgroundMigration.update({
where: {
- id: BackgroundMigrationManager.activeMigration.id,
+ id: active.id,
workerId: BackgroundMigrationManager.workerId,
},
data: {
@@ -130,7 +157,7 @@ export class BackgroundMigrationManager {
// Only mark as complete if still active. Otherwise, it was aborted.
await prisma.backgroundMigration.update({
where: {
- id: BackgroundMigrationManager.activeMigration.id,
+ id: active.id,
workerId: BackgroundMigrationManager.workerId,
},
data: {
@@ -139,16 +166,16 @@ export class BackgroundMigrationManager {
},
});
logger.info(
- `[Background Migration] Finished background migration ${BackgroundMigrationManager.activeMigration.name}`,
+ `[Background Migration] Finished background migration ${active.name}`,
);
}
} catch (err) {
logger.error(
- `[Background Migration] Failed to run background migration ${BackgroundMigrationManager.activeMigration.name}: ${err}`,
+ `[Background Migration] Failed to run background migration ${active.name}: ${err}`,
);
await prisma.backgroundMigration.update({
where: {
- id: BackgroundMigrationManager.activeMigration.id,
+ id: active.id,
workerId: BackgroundMigrationManager.workerId,
},
data: {
diff --git a/worker/src/backgroundMigrations/createRootSpansFromTraces.ts b/worker/src/backgroundMigrations/createRootSpansFromTraces.ts
new file mode 100644
index 0000000000..79db7de174
--- /dev/null
+++ b/worker/src/backgroundMigrations/createRootSpansFromTraces.ts
@@ -0,0 +1,137 @@
+import {
+ BaseChunkTodo,
+ ChunkedClickhouseBackfillMigration,
+ ResolvedChunkedBackfillConfig,
+ assertSafePartition,
+ loadPartitionsFromClickhouse,
+ runBackfillMigrationCli,
+} from "./utils/backfillBase";
+
+// Hard-coded UUID identifying the row in background_migrations.
+// Must match the Prisma migration that registers this row.
+const backgroundMigrationId = "8e1f4a2b-5c63-4d8e-9a47-1b2f3c4d5e6f";
+
+const LOG_PREFIX = "[Backfill Root Spans]";
+
+/**
+ * V4 chain step 1: materializes one virtual root span per trace into
+ * `events_full`, chunked by yyyymm traces partition. Traces referenced by a
+ * dataset run item are skipped β€” M4 owns those end-to-end.
+ */
+export default class CreateRootSpansFromTraces extends ChunkedClickhouseBackfillMigration {
+ protected readonly migrationId = backgroundMigrationId;
+ protected readonly logPrefix = LOG_PREFIX;
+ protected readonly requiredTables = [
+ "events_full",
+ "traces",
+ "events_core",
+ "events_core_mv",
+ "dataset_run_items_rmt",
+ ];
+
+ protected async enumerateChunks(
+ config: ResolvedChunkedBackfillConfig,
+ ): Promise<BaseChunkTodo[]> {
+ return loadPartitionsFromClickhouse(
+ "traces",
+ config.partitions,
+ this.logPrefix,
+ );
+ }
+
+ /**
+ * Builds the INSERT that materializes one virtual root span per trace into
+ * `events_full`. It
+ * - skips DRI-referenced traces entirely (M4 materializes those traces
+ * end-to-end, root + every observation, with experiment enrichment),
+ * - is scoped to a single yyyymm partition so the scan is bounded.
+ *
+ * Unmerged duplicate trace rows are copied as-is: each carries its own
+ * `event_ts`, so the ReplacingMergeTree semantics of `events_full` collapse
+ * them to the latest version.
+ */
+ protected buildChunkQuery(todo: BaseChunkTodo): {
+ query: string;
+ params: Record<string, unknown>;
+ } {
+ assertSafePartition(todo.partition);
+
+ const query = `
+ INSERT INTO events_full (
+ project_id, trace_id, span_id, parent_span_id, start_time,
+ name, type, environment, version, release, tags,
+ trace_name, user_id, session_id, public, bookmarked, level,
+ model_parameters,
+ provided_usage_details, usage_details, provided_cost_details, cost_details,
+ tool_definitions, tool_calls, tool_call_names,
+ input, output,
+ metadata_names, metadata_values,
+ source, blob_storage_file_path, event_bytes,
+ created_at, updated_at, event_ts, is_deleted
+ )
+ SELECT
+ t.project_id,
+ t.id AS trace_id,
+ concat('t-', t.id) AS span_id,
+ '' AS parent_span_id,
+ t.timestamp AS start_time,
+ t.name AS name,
+ 'SPAN' AS type,
+ t.environment,
+ coalesce(t.version, '') AS version,
+ coalesce(t.release, '') AS release,
+ t.tags AS tags,
+ t.name AS trace_name,
+ coalesce(t.user_id, '') AS user_id,
+ coalesce(t.session_id, '') AS session_id,
+ t.public AS public,
+ t.bookmarked AS bookmarked,
+ 'DEFAULT' AS level,
+ '{}' AS model_parameters,
+ map() AS provided_usage_details,
+ map() AS usage_details,
+ map() AS provided_cost_details,
+ map() AS cost_details,
+ map() AS tool_definitions,
+ [] AS tool_calls,
+ [] AS tool_call_names,
+ coalesce(t.input, '') AS input,
+ coalesce(t.output, '') AS output,
+ mapKeys(t.metadata) AS metadata_names,
+ mapValues(t.metadata) AS metadata_values,
+ multiIf(mapContains(t.metadata, 'resourceAttributes'), 'otel-backfill', 'ingestion-api-backfill') AS source,
+ '' AS blob_storage_file_path,
+ 0 AS event_bytes,
+ t.created_at,
+ t.updated_at,
+ t.event_ts,
+ t.is_deleted
+ FROM traces t
+ WHERE t._partition_id = {partition: String}
+ -- DRI-referenced traces are materialized end-to-end by M4 (root + every
+ -- observation, with experiment enrichment), so M1 skips them to keep
+ -- ownership disjoint and avoid plain-vs-enriched root collisions. Relies
+ -- on the same per-project co-location as the rest of the chain.
+ AND (t.project_id, t.id) NOT IN (
+ SELECT project_id, trace_id FROM dataset_run_items_rmt
+ )
+ SETTINGS
+ type_json_skip_duplicated_paths = 1
+ `;
+
+ return {
+ query,
+ params: { partition: todo.partition },
+ };
+ }
+}
+
+// ============================================================================
+// CLI Entry Point
+// ============================================================================
+
+if (require.main === module) {
+ runBackfillMigrationCli(() => new CreateRootSpansFromTraces(), {
+ logPrefix: LOG_PREFIX,
+ });
+}
diff --git a/worker/src/backgroundMigrations/dropPidTidSortingTables.ts b/worker/src/backgroundMigrations/dropPidTidSortingTables.ts
new file mode 100644
index 0000000000..80d776c88d
--- /dev/null
+++ b/worker/src/backgroundMigrations/dropPidTidSortingTables.ts
@@ -0,0 +1,142 @@
+import { IBackgroundMigration } from "./IBackgroundMigration";
+import { commandClickhouse, logger } from "@langfuse/shared/src/server";
+import { parseArgs } from "node:util";
+import {
+ checkPredecessorMigrationFinalized,
+ onClusterClause,
+} from "./utils/backfillBase";
+
+// Hard-coded UUID identifying the row in background_migrations. Must match the
+// Prisma migration that registers this row.
+const backgroundMigrationId = "b3f1c5d8-9e47-4a26-8b3f-5c6d7e8f9a01";
+
+const LOG_PREFIX = "[Drop PID/TID sorting tables]";
+
+// ============================================================================
+// Migration class
+// ============================================================================
+
+/**
+ * Cleanup migration that drops the scratch table created by the V4 historic
+ * backfill chain (M2 β†’ M3 β†’ M4):
+ *
+ * - `observations_pid_tid_sorting` β€” populated by M2, read by M3, M4.
+ *
+ * This is a single-step migration with no chunking. It is gated by
+ * `LANGFUSE_BACKGROUND_MIGRATION_V4_DROP_PID_TID_SORTING_TABLES` so self-hosters can keep
+ * the scratch table around for forensics/restartability until they're
+ * confident the new path is healthy.
+ */
+export default class DropPidTidSortingTables implements IBackgroundMigration {
+ private isAborted = false;
+
+ // ============================================================================
+ // Validate
+ // ============================================================================
+
+ async validate(
+ _args: Record<string, unknown>,
+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {
+ return checkPredecessorMigrationFinalized(
+ "9d4f8a12-7b35-4e6c-9f48-a2b3c4d5e6f7",
+ "20260701_v4_step_4_backfill_events_full_from_dataset_run_items",
+ );
+ }
+
+ // ============================================================================
+ // Run
+ // ============================================================================
+
+ async run(_args: Record<string, unknown>): Promise<void> {
+ logger.info(`${LOG_PREFIX} Starting cleanup of V4 backfill scratch tables`);
+
+ const tables = ["observations_pid_tid_sorting"];
+
+ for (const table of tables) {
+ if (this.isAborted) {
+ logger.info(`${LOG_PREFIX} Aborted before dropping ${table}`);
+ return;
+ }
+
+ const onCluster = onClusterClause();
+ // `IF EXISTS` keeps the migration idempotent β€” re-running the row (or
+ // running it on a deployment that never created the scratch tables) is
+ // a no-op rather than an error.
+ const sql = `DROP TABLE IF EXISTS ${table} ${onCluster} SYNC`.trim();
+
+ logger.info(`${LOG_PREFIX} Dropping ${table}`);
+ try {
+ await commandClickhouse({
+ query: sql,
+ tags: {
+ surface: "worker",
+ route: `background-migration.dropPidTidSortingTables:${table}`,
+ },
+ });
+ logger.info(`${LOG_PREFIX} Dropped ${table}`);
+ } catch (error) {
+ logger.error(`${LOG_PREFIX} Failed to drop ${table}`, error);
+ throw error;
+ }
+ }
+
+ logger.info(`${LOG_PREFIX} Cleanup complete`);
+ }
+
+ // ============================================================================
+ // Abort
+ // ============================================================================
+
+ async abort(): Promise<void> {
+ logger.info(`${LOG_PREFIX} Aborting drop migration`);
+ this.isAborted = true;
+ }
+}
+
+// ============================================================================
+// CLI entry point
+// ============================================================================
+
+async function main(): Promise<void> {
+ process.on("unhandledRejection", (reason) => {
+ logger.error(
+ `${LOG_PREFIX} Unhandled rejection - process will exit`,
+ reason,
+ );
+ process.exit(1);
+ });
+
+ process.on("uncaughtException", (error) => {
+ logger.error(`${LOG_PREFIX} Uncaught exception - process will exit`, error);
+ process.exit(1);
+ });
+
+ parseArgs({ options: {} });
+
+ const migration = new DropPidTidSortingTables();
+ const validation = await migration.validate({});
+
+ if (!validation.valid) {
+ logger.error(
+ `${LOG_PREFIX} Validation failed: ${validation.invalidReason}`,
+ );
+ process.exit(1);
+ }
+
+ await migration.run({});
+}
+
+if (require.main === module) {
+ main()
+ .then(() => {
+ process.exit(0);
+ })
+ .catch((error) => {
+ logger.error(`${LOG_PREFIX} Migration execution failed: ${error}`, error);
+ process.exit(1);
+ });
+}
+
+// Exported so callers can reference the canonical UUID without importing the
+// default export.
+export { backgroundMigrationId };
diff --git a/worker/src/backgroundMigrations/rewriteObservationsToPidTidSorting.ts b/worker/src/backgroundMigrations/rewriteObservationsToPidTidSorting.ts
new file mode 100644
index 0000000000..93497ae909
--- /dev/null
+++ b/worker/src/backgroundMigrations/rewriteObservationsToPidTidSorting.ts
@@ -0,0 +1,321 @@
+import { commandClickhouse, logger } from "@langfuse/shared/src/server";
+import { env } from "../env";
+import {
+ BaseChunkTodo,
+ ChunkedBackfillState,
+ ChunkedClickhouseBackfillMigration,
+ ResolvedChunkedBackfillConfig,
+ assertSafePartition,
+ detectTableEngine,
+ loadPartitionsFromClickhouse,
+ onClusterClause,
+ runBackfillMigrationCli,
+} from "./utils/backfillBase";
+
+// Hard-coded UUID identifying the row in background_migrations.
+// Must match the Prisma migration that registers this row.
+const backgroundMigrationId = "9c2d5a4f-7b8e-4f6a-a91c-3e5d7f8a2b1c";
+
+const LOG_PREFIX = "[Backfill PidTid Sorting]";
+
+// ============================================================================
+// Cluster-aware DDL helpers
+// ============================================================================
+
+/**
+ * Returns the engine clause for the scratch table. We use the replicated
+ * variant only on clusters; single-node deployments use the unreplicated
+ * engine.
+ */
+function replacingMergeTreeEngine(): string {
+ if (env.CLICKHOUSE_CLUSTER_ENABLED === "true") {
+ return "ReplicatedReplacingMergeTree(event_ts, is_deleted)";
+ }
+ return "ReplacingMergeTree(event_ts, is_deleted)";
+}
+
+/**
+ * V4 chain step 2: copies `observations` into the
+ * `observations_pid_tid_sorting` scratch table whose sort key is reordered to
+ * `(project_id, trace_id, id)`, chunked by yyyymm observations partition.
+ */
+export default class RewriteObservationsToPidTidSorting extends ChunkedClickhouseBackfillMigration {
+ protected readonly migrationId = backgroundMigrationId;
+ protected readonly logPrefix = LOG_PREFIX;
+ protected readonly requiredTables = ["observations"];
+
+ // ==========================================================================
+ // Lazy DDL: scratch table
+ // ==========================================================================
+
+ /**
+ * Lazy-create the scratch table so it does not pollute fresh installs.
+ */
+ protected async afterTablesValidated(): Promise<void> {
+ await this.ensureScratchTable();
+ }
+
+ /**
+ * Creates `observations_pid_tid_sorting` if it does not exist. The schema
+ * mirrors `observations` but the
+ * sort key is reordered to `(project_id, trace_id, id)` so M3 can perform
+ * a merge-sort join against this table without an explicit re-sort.
+ */
+ private async ensureScratchTable(): Promise<void> {
+ const ddl = `
+ CREATE TABLE IF NOT EXISTS observations_pid_tid_sorting ${onClusterClause()} (
+ \`id\` String,
+ \`trace_id\` String,
+ \`project_id\` String,
+ \`environment\` LowCardinality(String) DEFAULT 'default',
+ \`type\` LowCardinality(String),
+ \`parent_observation_id\` Nullable(String),
+ \`start_time\` DateTime64(3),
+ \`end_time\` Nullable(DateTime64(3)),
+ \`name\` String,
+ \`metadata\` Map(LowCardinality(String), String),
+ \`level\` LowCardinality(String),
+ \`status_message\` Nullable(String),
+ \`version\` Nullable(String),
+ \`input\` Nullable(String) CODEC(ZSTD(3)),
+ \`output\` Nullable(String) CODEC(ZSTD(3)),
+ \`provided_model_name\` Nullable(String),
+ \`internal_model_id\` Nullable(String),
+ \`model_parameters\` Nullable(String),
+ \`provided_usage_details\` Map(LowCardinality(String), UInt64),
+ \`usage_details\` Map(LowCardinality(String), UInt64),
+ \`provided_cost_details\` Map(LowCardinality(String), Decimal64(12)),
+ \`cost_details\` Map(LowCardinality(String), Decimal64(12)),
+ \`total_cost\` Nullable(Decimal64(12)),
+ \`completion_start_time\` Nullable(DateTime64(3)),
+ \`prompt_id\` Nullable(String),
+ \`prompt_name\` Nullable(String),
+ \`prompt_version\` Nullable(UInt16),
+ \`usage_pricing_tier_id\` Nullable(String),
+ \`usage_pricing_tier_name\` Nullable(String),
+ \`tool_definitions\` Map(String, String) DEFAULT map(),
+ \`tool_calls\` Array(String) DEFAULT [],
+ \`tool_call_names\` Array(String) DEFAULT [],
+ \`created_at\` DateTime64(3) DEFAULT now(),
+ \`updated_at\` DateTime64(3) DEFAULT now(),
+ event_ts DateTime64(3),
+ is_deleted UInt8
+ ) ENGINE = ${replacingMergeTreeEngine()}
+ PARTITION BY toYYYYMM(start_time)
+ PRIMARY KEY (project_id, trace_id)
+ ORDER BY (project_id, trace_id, id)
+ `;
+
+ logger.info(
+ `${this.logPrefix} Ensuring observations_pid_tid_sorting exists`,
+ );
+
+ await commandClickhouse({
+ query: ddl,
+ tags: {
+ surface: "worker",
+ route: "background-migration.ensureScratchTable",
+ },
+ });
+ }
+
+ // ==========================================================================
+ // Merge control
+ // ==========================================================================
+
+ private async stopMergesOnScratchTable(): Promise<void> {
+ const engine = await detectTableEngine("observations_pid_tid_sorting");
+ const isSharedMergeTree = engine.startsWith("Shared");
+ const isReplicatedMergeTree = engine.startsWith("Replicated");
+
+ logger.info(
+ `${this.logPrefix} Stopping merges on observations_pid_tid_sorting (engine=${engine || "unknown"})`,
+ );
+
+ if (isSharedMergeTree) {
+ // ClickHouse Cloud (SharedMergeTree) does not support `SYSTEM STOP MERGES`.
+ // The documented equivalent is the per-table setting below, which is
+ // assignment-scoped and persists until explicitly reset.
+ await commandClickhouse({
+ query: `ALTER TABLE observations_pid_tid_sorting MODIFY SETTING shared_merge_tree_disable_merges_and_mutations_assignment = 1`,
+ tags: {
+ surface: "worker",
+ route: "background-migration.stopMerges",
+ },
+ });
+ } else {
+ // Self-hosted MergeTree. `SYSTEM STOP MERGES` takes an in-memory action
+ // lock (held by the ActionLocksManager) that is *not* persisted: it is
+ // reset on server restart, so on its own it is not a durable freeze
+ // across the M2 -> M3 gap.
+ await commandClickhouse({
+ query: `SYSTEM STOP MERGES ${onClusterClause()} observations_pid_tid_sorting`,
+ tags: {
+ surface: "worker",
+ route: "background-migration.stopMerges",
+ },
+ });
+
+ // For the replicated engine, persist the freeze in table metadata on top
+ // of the in-memory lock so it survives restarts and holds on every
+ // replica: stop enqueuing new merges (`max_replicated_merges_in_queue=0`)
+ // and stop any replica from executing a merge locally
+ // (`always_fetch_merged_part=1`).
+ // See https://github.com/ClickHouse/ClickHouse/issues/22830.
+ if (isReplicatedMergeTree) {
+ await commandClickhouse({
+ query: `ALTER TABLE observations_pid_tid_sorting ${onClusterClause()} MODIFY SETTING max_replicated_merges_in_queue = 0, always_fetch_merged_part = 1`,
+ tags: {
+ surface: "worker",
+ route: "background-migration.stopMerges",
+ },
+ });
+ }
+ }
+ }
+
+ /**
+ * Drives every replica to drain its replication queue so each node's
+ * `system.parts` reflects the full, post-backfill part set before M3 reads
+ * it. This is the convergence half of the pair: the freeze above keeps the
+ * layout from drifting, and this makes every node actually current.
+ *
+ * Only meaningful on the replicated engine β€” a single-node plain MergeTree
+ * has nothing to sync (and `SYSTEM SYNC REPLICA` errors on it), and
+ * Cloud/SharedMergeTree keeps part metadata centrally consistent already.
+ * `STRICT` waits for the queue to fully empty so a merge that committed just
+ * before the freeze is propagated everywhere. `ON CLUSTER` fans the sync to
+ * every node, and the default `distributed_ddl_output_mode='throw'` surfaces
+ * an unreachable replica as a hard failure β€” which keeps M2 unfinished (and
+ * therefore blocks M3) until the cluster converges, instead of advancing on
+ * a half-synced cluster.
+ */
+ private async syncReplicasOnScratchTable(): Promise<void> {
+ const engine = await detectTableEngine("observations_pid_tid_sorting");
+ if (!engine.startsWith("Replicated")) {
+ logger.info(
+ `${this.logPrefix} Skipping SYSTEM SYNC REPLICA (engine=${engine || "unknown"} is not replicated)`,
+ );
+ return;
+ }
+
+ logger.info(
+ `${this.logPrefix} Syncing all replicas of observations_pid_tid_sorting`,
+ );
+ await commandClickhouse({
+ query: `SYSTEM SYNC REPLICA ${onClusterClause()} observations_pid_tid_sorting STRICT`,
+ tags: {
+ surface: "worker",
+ route: "background-migration.syncReplica",
+ },
+ });
+ }
+
+ // ==========================================================================
+ // Chunk enumeration and query building
+ // ==========================================================================
+
+ protected async enumerateChunks(
+ config: ResolvedChunkedBackfillConfig,
+ ): Promise<BaseChunkTodo[]> {
+ return loadPartitionsFromClickhouse(
+ "observations",
+ config.partitions,
+ this.logPrefix,
+ );
+ }
+
+ /**
+ * Builds the INSERT that copies one yyyymm partition of `observations` into
+ * `observations_pid_tid_sorting`. Columns are enumerated explicitly in the
+ * same order on both sides to avoid surprises when CH adds new columns.
+ */
+ protected buildChunkQuery(todo: BaseChunkTodo): {
+ query: string;
+ params: Record<string, unknown>;
+ } {
+ assertSafePartition(todo.partition);
+
+ const query = `
+ INSERT INTO observations_pid_tid_sorting (
+ id, trace_id, project_id, environment, type, parent_observation_id,
+ start_time, end_time, name, metadata, level, status_message, version,
+ input, output,
+ provided_model_name, internal_model_id, model_parameters,
+ provided_usage_details, usage_details, provided_cost_details, cost_details,
+ total_cost, completion_start_time,
+ prompt_id, prompt_name, prompt_version,
+ usage_pricing_tier_id, usage_pricing_tier_name,
+ tool_definitions, tool_calls, tool_call_names,
+ created_at, updated_at, event_ts, is_deleted
+ )
+ SELECT
+ id, trace_id, project_id, environment, type, parent_observation_id,
+ start_time, end_time, name, metadata, level, status_message, version,
+ input, output,
+ provided_model_name, internal_model_id, model_parameters,
+ provided_usage_details, usage_details, provided_cost_details, cost_details,
+ total_cost, completion_start_time,
+ prompt_id, prompt_name, prompt_version,
+ usage_pricing_tier_id, usage_pricing_tier_name,
+ tool_definitions, tool_calls, tool_call_names,
+ created_at, updated_at, event_ts, is_deleted
+ FROM observations
+ WHERE _partition_id = {partition: String}
+ SETTINGS
+ type_json_skip_duplicated_paths = 1
+ `;
+
+ return {
+ query,
+ params: { partition: todo.partition },
+ };
+ }
+
+ // ==========================================================================
+ // Completion hooks
+ // ==========================================================================
+
+ /**
+ * Finalize the scratch table for downstream processing: freeze its part
+ * layout, then converge every replica onto that frozen layout. M3 depends on
+ * the post-backfill parts staying frozen and identical across replicas; it
+ * owns re-enabling merges (or replacing the table entirely). Syncing here
+ * gates the chain β€” a throw leaves M2 unfinished and M3 blocked until the
+ * cluster converges, rather than advancing on a half-synced cluster.
+ */
+ protected async onBackfillSucceeded(
+ _state: ChunkedBackfillState<BaseChunkTodo>,
+ ): Promise<void> {
+ await this.stopMergesOnScratchTable();
+ await this.syncReplicasOnScratchTable();
+ logger.info(
+ `${this.logPrefix} Froze and synced observations_pid_tid_sorting for downstream processing`,
+ );
+ }
+
+ /**
+ * Backfill is incomplete. Leave merges running so a later re-run with
+ * --retry-failed can insert into a table whose parts still merge; freezing a
+ * partially populated table would let retried inserts pile up as unmerged
+ * parts (part explosion) until M5 drops it.
+ */
+ protected async onBackfillFailed(
+ state: ChunkedBackfillState<BaseChunkTodo>,
+ ): Promise<void> {
+ const failed = state.todos.filter((t) => t.status === "failed").length;
+ logger.error(
+ `${this.logPrefix} Migration completed with ${failed} failed chunks; leaving merges enabled on observations_pid_tid_sorting for --retry-failed`,
+ );
+ }
+}
+
+// ============================================================================
+// CLI Entry Point
+// ============================================================================
+
+if (require.main === module) {
+ runBackfillMigrationCli(() => new RewriteObservationsToPidTidSorting(), {
+ logPrefix: LOG_PREFIX,
+ });
+}
diff --git a/worker/src/backgroundMigrations/utils/backfillBase.ts b/worker/src/backgroundMigrations/utils/backfillBase.ts
new file mode 100644
index 0000000000..8714fec482
--- /dev/null
+++ b/worker/src/backgroundMigrations/utils/backfillBase.ts
@@ -0,0 +1,903 @@
+import { randomUUID } from "crypto";
+import { parseArgs } from "node:util";
+import {
+ clickhouseClient,
+ commandClickhouse,
+ getQueryError,
+ logger,
+ pollQueryStatus,
+ queryClickhouse,
+ sleep,
+ type QueryStatus,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { env } from "../../env";
+import { IBackgroundMigration } from "../IBackgroundMigration";
+
+// ============================================================================
+// Shared types
+// ============================================================================
+
+export interface BaseChunkTodo {
+ id: string;
+ partition: string;
+ status: "pending" | "in_progress" | "completed" | "failed";
+ queryId?: string;
+ startedAt?: string;
+ completedAt?: string;
+ error?: string;
+ retryCount?: number;
+}
+
+export interface ChunkedBackfillArgs {
+ concurrency?: number;
+ pollIntervalMs?: number;
+ maxRetries?: number;
+ retryFailed?: boolean;
+ envGate?: string;
+ /**
+ * Optional list of yyyymm partitions to restrict scope. Only honored by
+ * migrations whose `enumerateChunks` supports partition restriction.
+ */
+ partitions?: string[];
+}
+
+export interface ResolvedChunkedBackfillConfig {
+ concurrency: number;
+ pollIntervalMs: number;
+ maxRetries: number;
+ partitions?: string[];
+}
+
+export interface ChunkedBackfillState<T extends BaseChunkTodo> {
+ phase: "init" | "loading_chunks" | "backfill" | "completed";
+ chunksLoaded: boolean;
+ todos: T[];
+ activeQueries: string[];
+ config: Partial<ResolvedChunkedBackfillConfig>;
+}
+
+// ============================================================================
+// Helpers
+// ============================================================================
+
+export function generateQueryId(chunkId: string): string {
+ return `backfill-${chunkId}-${randomUUID().slice(0, 8)}`;
+}
+
+/**
+ * `partition_id` is either a 6-digit yyyymm string or the literal "REST".
+ */
+const PARTITION_RE = /^[0-9]{6}$|^REST$/;
+export function assertSafePartition(partition: string): void {
+ if (!PARTITION_RE.test(partition)) {
+ throw new Error(`Invalid partition_id: ${partition}`);
+ }
+}
+
+// ============================================================================
+// Cluster-aware helpers
+// ============================================================================
+
+/**
+ * Returns `ON CLUSTER <name>` when running against a clustered ClickHouse
+ * deployment, an empty string otherwise. Shared by every chain step that
+ * issues DDL or SYSTEM commands so they fan out to all nodes consistently.
+ */
+export function onClusterClause(): string {
+ if (env.CLICKHOUSE_CLUSTER_ENABLED === "true") {
+ return `ON CLUSTER ${env.CLICKHOUSE_CLUSTER_NAME}`;
+ }
+ return "";
+}
+
+/**
+ * Returns the engine ClickHouse actually picked for a table. On ClickHouse
+ * Cloud the requested engine is silently rewritten to a `Shared*` variant
+ * (e.g. `SharedReplacingMergeTree`), and single-node deployments use the plain
+ * (non-`Replicated*`) engine β€” so the prefix is the reliable way to branch on
+ * deployment topology. Returns "" if the table does not exist.
+ */
+export async function detectTableEngine(table: string): Promise<string> {
+ const rows = await queryClickhouse<{ engine: string }>({
+ query: `
+ SELECT engine
+ FROM system.tables
+ WHERE database = currentDatabase()
+ AND name = {table: String}
+ `,
+ params: { table },
+ tags: {
+ surface: "worker",
+ route: "background-migration.detectTableEngine",
+ },
+ });
+ return rows[0]?.engine ?? "";
+}
+
+// ============================================================================
+// Migration chain dependency guard
+// ============================================================================
+
+/**
+ * Returns a validation failure unless the prerequisite background-migration row
+ * has finished cleanly (`finishedAt` set, `failedAt` null).
+ *
+ * The `BackgroundMigrationManager` has no dependency model β€” it runs every eligible
+ * row in name order and marks each finished/failed independently, so a failed
+ * upstream step does NOT by itself stop a downstream step from running on
+ * partial data. Each downstream step calls this from its `validate()`, which
+ * routes through the manager's validation-failure path and records `failedAt`.
+ * Because the next step in turn guards on its own predecessor, a single failure
+ * transitively halts the rest of the chain.
+ */
+export async function checkPredecessorMigrationFinalized(
+ predecessorId: string,
+ predecessorName: string,
+): Promise<{ valid: boolean; invalidReason: string | undefined }> {
+ const predecessor = await prisma.backgroundMigration.findUnique({
+ where: { id: predecessorId },
+ select: { finishedAt: true, failedAt: true },
+ });
+
+ if (!predecessor) {
+ return {
+ valid: false,
+ invalidReason: `Prerequisite migration ${predecessorName} (${predecessorId}) is not registered`,
+ };
+ }
+ if (predecessor.failedAt) {
+ return {
+ valid: false,
+ invalidReason: `Prerequisite migration ${predecessorName} failed at ${predecessor.failedAt.toISOString()}; resolve it and clear failedAt before this step can run`,
+ };
+ }
+ if (!predecessor.finishedAt) {
+ return {
+ valid: false,
+ invalidReason: `Prerequisite migration ${predecessorName} has not finished yet`,
+ };
+ }
+
+ return { valid: true, invalidReason: undefined };
+}
+
+// ============================================================================
+// Partition discovery
+// ============================================================================
+
+/**
+ * Lists active yyyymm partitions of a ClickHouse table from `system.parts`,
+ * newest-first. Skips the meta partitions that aren't yyyymm data ranges:
+ *
+ * - `all` β€” appears on tables defined without a PARTITION BY clause.
+ * - `patch-%` β€” used by patch tables for ad hoc data corrections.
+ *
+ * Optionally restricted to a caller-provided list of yyyymm partitions.
+ */
+export async function loadPartitionsFromClickhouse(
+ table: string,
+ restrictTo?: string[],
+ logPrefix = "[Backfill]",
+): Promise<BaseChunkTodo[]> {
+ logger.info(`${logPrefix} Discovering ${table} partitions from system.parts`);
+
+ const rows = await queryClickhouse<{ partition_id: string }>({
+ query: `
+ SELECT DISTINCT partition_id
+ FROM system.parts
+ WHERE table = {table: String}
+ AND database = currentDatabase()
+ AND active = 1
+ AND partition_id NOT LIKE 'patch-%'
+ AND partition_id != 'all'
+ ORDER BY partition_id DESC
+ `,
+ params: { table },
+ tags: {
+ surface: "worker",
+ route: "background-migration.loadPartitionsFromClickhouse",
+ },
+ });
+
+ const partitions = rows.map((r) => r.partition_id);
+
+ const filterSet =
+ restrictTo && restrictTo.length > 0 ? new Set(restrictTo) : null;
+ const selected = filterSet
+ ? partitions.filter((p) => filterSet.has(p))
+ : partitions;
+
+ logger.info(
+ `${logPrefix} Loaded ${selected.length} partitions: ${selected.join(", ")}`,
+ );
+
+ return selected.map((partition) => ({
+ id: `p-${partition}`,
+ partition,
+ status: "pending" as const,
+ }));
+}
+
+// ============================================================================
+// Fire query (long-running, abort-and-poll pattern)
+// ============================================================================
+
+export interface FireQueryRetrySettings {
+ retry0?: Record<string, string | number>;
+ retry1?: Record<string, string | number>;
+ retry2?: Record<string, string | number>;
+}
+
+const DEFAULT_RETRY_SETTINGS: FireQueryRetrySettings = {
+ retry0: {},
+ retry1: { max_block_size: "4096" },
+ retry2: { max_threads: 1, max_insert_threads: "1", max_block_size: "2048" },
+};
+
+export interface FireQueryOptions {
+ query: string;
+ queryId: string;
+ params?: Record<string, unknown>;
+ /**
+ * Which attempt this is for the chunk (0-based). Only selects the
+ * progressively more conservative ClickHouse settings from `retrySettings`;
+ * retrying itself is the caller's responsibility.
+ */
+ attemptNumber?: number;
+ retrySettings?: FireQueryRetrySettings;
+ initialWaitMs?: number;
+ retryWaitMs?: number;
+ logPrefix?: string;
+}
+
+/**
+ * Fires a long-running ClickHouse query, confirms it's tracked in
+ * system.processes, then aborts the HTTP connection so the query continues
+ * server-side and we poll for completion via pollQueryStatus.
+ */
+export async function fireQuery({
+ query,
+ queryId,
+ params,
+ attemptNumber = 0,
+ retrySettings = DEFAULT_RETRY_SETTINGS,
+ initialWaitMs = 10_000,
+ retryWaitMs = 30_000,
+ logPrefix = "[Backfill]",
+}: FireQueryOptions): Promise<void> {
+ logger.info(`${logPrefix} Firing query ${queryId}`);
+
+ const abortController = new AbortController();
+
+ const retrySetting =
+ attemptNumber > 1
+ ? (retrySettings.retry2 ?? {})
+ : attemptNumber > 0
+ ? (retrySettings.retry1 ?? {})
+ : (retrySettings.retry0 ?? {});
+
+ if (attemptNumber > 0) {
+ logger.info(
+ `${logPrefix} Applying retry settings for query ${queryId}: ${JSON.stringify(retrySetting)} (attempt ${attemptNumber})`,
+ );
+ }
+
+ // The rejection handler must attach in the same tick the promise is created:
+ // the command can reject at any point (fast HTTP/auth/parse errors, the
+ // expected abort below) and an unhandled rejection kills the worker process
+ // via the migrations' unhandledRejection handlers.
+ let earlyError: unknown = null;
+ const queryPromise = commandClickhouse({
+ query,
+ params,
+ // Set the server-side query_id so pollQueryStatus can track this query in
+ // system.processes / system.query_log after we abort the HTTP connection.
+ // (Post-#14493 commandClickhouse only honors the top-level `queryId`; a
+ // `queryId` inside `tags` is dropped by tag normalization.)
+ queryId,
+ tags: {
+ surface: "worker",
+ route: "background-migration.fireQuery",
+ },
+ clickhouseSettings: { ...retrySetting },
+ abortSignal: abortController.signal,
+ }).catch((err) => {
+ if (err?.name === "AbortError" || err?.message?.includes("aborted")) {
+ logger.debug(
+ `${logPrefix} Query ${queryId} HTTP connection aborted as expected`,
+ );
+ } else {
+ earlyError = err;
+ logger.info(
+ `${logPrefix} Query ${queryId} promise rejected: ${err?.message}`,
+ err,
+ );
+ }
+ });
+
+ // Surface fast failures (connection refused, auth, SQL parse errors) right
+ // away instead of polling for a query that never started.
+ await Promise.race([queryPromise, sleep(initialWaitMs)]);
+ if (earlyError) {
+ throw earlyError instanceof Error
+ ? earlyError
+ : new Error(String(earlyError));
+ }
+
+ try {
+ const status = await pollQueryStatus(queryId);
+ if (status === "not_found") {
+ await sleep(retryWaitMs);
+ const retryStatus = await pollQueryStatus(queryId);
+ if (retryStatus === "not_found") {
+ throw new Error(`Query ${queryId} failed to start on server`);
+ }
+ }
+ } catch (error) {
+ logger.error(
+ `${logPrefix} Error verifying query ${queryId} started`,
+ error,
+ );
+ throw error;
+ }
+
+ logger.info(
+ `${logPrefix} Query ${queryId} confirmed running, aborting HTTP connection`,
+ );
+ abortController.abort();
+}
+
+// ============================================================================
+// Recovery
+// ============================================================================
+
+/**
+ * Reattach to in-flight queries from a previous worker run by polling each
+ * queryId. Updates each todo in-place with the recovered status.
+ * Usually, persisted afterwards by a state update, i.e. relies on mutating behaviour
+ * outside the function.
+ * Returns the subset that ClickHouse still reports as running so the caller
+ * can keep tracking them.
+ */
+export async function recoverInProgressTodos<T extends BaseChunkTodo>(
+ todos: T[],
+ logPrefix = "[Backfill]",
+): Promise<T[]> {
+ const inProgress = todos.filter(
+ (t) => t.status === "in_progress" && t.queryId,
+ );
+ if (inProgress.length === 0) return [];
+
+ logger.info(
+ `${logPrefix} Recovering ${inProgress.length} in-progress chunks`,
+ );
+ const stillRunning: T[] = [];
+
+ for (const todo of inProgress) {
+ try {
+ const status = await pollQueryStatus(todo.queryId!);
+
+ if (status === "completed") {
+ todo.status = "completed";
+ todo.completedAt = new Date().toISOString();
+ logger.info(`${logPrefix} Recovered chunk ${todo.id} as completed`);
+ } else if (status === "failed") {
+ todo.status = "pending";
+ todo.retryCount = (todo.retryCount || 0) + 1;
+ const error = await getQueryError(todo.queryId!);
+ logger.warn(
+ `${logPrefix} Recovered chunk ${todo.id} as failed, will retry: ${error}`,
+ );
+ } else if (status === "running") {
+ logger.info(
+ `${logPrefix} Recovered chunk ${todo.id} as still running (query ${todo.queryId}), will continue tracking`,
+ );
+ stillRunning.push(todo);
+ } else {
+ todo.status = "pending";
+ todo.queryId = undefined;
+ logger.warn(
+ `${logPrefix} Recovered chunk ${todo.id} as not_found, resetting to pending`,
+ );
+ }
+ } catch (error) {
+ logger.error(
+ `${logPrefix} Error during recovery polling for chunk ${todo.id}, resetting to pending`,
+ error,
+ );
+ todo.status = "pending";
+ todo.queryId = undefined;
+ }
+ }
+
+ return stillRunning;
+}
+
+// ============================================================================
+// Chunked backfill base migration
+// ============================================================================
+
+/**
+ * Base class for backfill migrations that split their work into chunks
+ * (partitions or parts), run one long-lived server-side ClickHouse query per
+ * chunk via `fireQuery`, and persist progress in `background_migrations.state`.
+ *
+ * `run()` drives a single sequential scheduler loop that polls active queries,
+ * applies completions/failures, and fills free concurrency slots.
+ *
+ * Subclasses provide the chunk enumeration and per-chunk query, plus optional
+ * hooks for lazy DDL, post-chunk verification, and completion side effects.
+ */
+export abstract class ChunkedClickhouseBackfillMigration<
+ T extends BaseChunkTodo = BaseChunkTodo,
+> implements IBackgroundMigration {
+ protected isAborted = false;
+ /**
+ * Set when `verifyCompletedChunk` reports a violation. The loop winds down
+ * (in-flight queries keep their recoverable bookkeeping) and `run()` throws
+ * this error so the manager records `failedAt`.
+ */
+ private haltError: Error | null = null;
+
+ /** Hard-coded UUID of the row in background_migrations. */
+ protected abstract readonly migrationId: string;
+ protected abstract readonly logPrefix: string;
+ /** ClickHouse tables that must exist before the migration may run. */
+ protected abstract readonly requiredTables: string[];
+ /** Optional chain guard evaluated first in validate(). */
+ protected readonly predecessor?: { id: string; name: string };
+
+ /** Enumerates the chunk todos. Called exactly once per migration lifetime. */
+ protected abstract enumerateChunks(
+ config: ResolvedChunkedBackfillConfig,
+ ): Promise<T[]>;
+
+ /** Builds the long-running INSERT for one chunk. */
+ protected abstract buildChunkQuery(todo: T): {
+ query: string;
+ params: Record<string, unknown>;
+ };
+
+ /** Hook: runs after required tables exist (e.g. lazy scratch-table DDL). */
+ protected async afterTablesValidated(): Promise<void> {}
+
+ /**
+ * Hook: verifies a chunk whose query completed. Returning an error message
+ * marks the chunk failed and halts the migration (`run()` throws it).
+ */
+ protected async verifyCompletedChunk(_todo: T): Promise<string | null> {
+ return null;
+ }
+
+ /** Hook: runs once after every chunk completed cleanly; may throw. */
+ protected async onBackfillSucceeded(
+ _state: ChunkedBackfillState<T>,
+ ): Promise<void> {}
+
+ /** Hook: runs when chunks failed permanently, right before run() throws. */
+ protected async onBackfillFailed(
+ _state: ChunkedBackfillState<T>,
+ ): Promise<void> {}
+
+ // ==========================================================================
+ // State management
+ // ==========================================================================
+
+ protected async loadState(): Promise<ChunkedBackfillState<T>> {
+ const migration = await prisma.backgroundMigration.findUnique({
+ where: { id: this.migrationId },
+ select: { state: true },
+ });
+
+ const defaultState: ChunkedBackfillState<T> = {
+ phase: "init",
+ chunksLoaded: false,
+ todos: [],
+ activeQueries: [],
+ config: {},
+ };
+
+ if (!migration || !migration.state) {
+ return defaultState;
+ }
+
+ const state = migration.state as Partial<ChunkedBackfillState<T>>;
+
+ return {
+ phase: state.phase ?? defaultState.phase,
+ chunksLoaded: state.chunksLoaded ?? defaultState.chunksLoaded,
+ todos: state.todos ?? defaultState.todos,
+ activeQueries: state.activeQueries ?? defaultState.activeQueries,
+ config: state.config ?? defaultState.config,
+ };
+ }
+
+ protected async updateState(state: ChunkedBackfillState<T>): Promise<void> {
+ await prisma.backgroundMigration.update({
+ where: { id: this.migrationId },
+ data: { state: state as any },
+ });
+ }
+
+ // ==========================================================================
+ // Validation
+ // ==========================================================================
+
+ async validate(
+ _args: Record<string, unknown>,
+ attempts = 5,
+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {
+ if (this.predecessor) {
+ const predecessor = await checkPredecessorMigrationFinalized(
+ this.predecessor.id,
+ this.predecessor.name,
+ );
+ if (!predecessor.valid) {
+ return predecessor;
+ }
+ }
+
+ for (let attempt = 0; ; attempt++) {
+ const missing = await this.findFirstMissingTable();
+ if (!missing) break;
+ if (attempt >= attempts) {
+ return {
+ valid: false,
+ invalidReason: `ClickHouse ${missing} table does not exist`,
+ };
+ }
+ logger.info(
+ `${this.logPrefix} ${missing} table does not exist. Retrying in 10s...`,
+ );
+ await sleep(10_000);
+ }
+
+ await this.afterTablesValidated();
+
+ logger.info(`${this.logPrefix} All prerequisites validated successfully`);
+
+ return { valid: true, invalidReason: undefined };
+ }
+
+ private async findFirstMissingTable(): Promise<string | null> {
+ const tables = await clickhouseClient().query({ query: "SHOW TABLES" });
+ const tableNames = (await tables.json()).data as { name: string }[];
+ return (
+ this.requiredTables.find(
+ (required) => !tableNames.some((r) => r.name === required),
+ ) ?? null
+ );
+ }
+
+ // ==========================================================================
+ // Main run loop
+ // ==========================================================================
+
+ async run(args: Record<string, unknown>): Promise<void> {
+ const start = Date.now();
+ const migrationArgs = args as ChunkedBackfillArgs;
+
+ const config: ResolvedChunkedBackfillConfig = {
+ concurrency: migrationArgs.concurrency ?? 1,
+ pollIntervalMs: migrationArgs.pollIntervalMs ?? 30_000,
+ maxRetries: migrationArgs.maxRetries ?? 3,
+ partitions: migrationArgs.partitions,
+ };
+
+ logger.info(
+ `${this.logPrefix} Starting backfill with config: ${JSON.stringify(config)}`,
+ );
+
+ const state = await this.loadState();
+ state.config = config;
+
+ // Phase 1: enumerate chunks (one-time)
+ if (!state.chunksLoaded) {
+ state.phase = "loading_chunks";
+ await this.updateState(state);
+
+ state.todos = await this.enumerateChunks(config);
+ state.chunksLoaded = true;
+ state.phase = "backfill";
+ await this.updateState(state);
+ }
+
+ // Phase 2: re-attach to queries left running by a previous worker
+ const stillRunning = await recoverInProgressTodos(
+ state.todos,
+ this.logPrefix,
+ );
+ await this.updateState(state);
+
+ // Phase 2.5: reset failed chunks to pending if --retry-failed was passed
+ if (migrationArgs.retryFailed) {
+ const failedChunks = state.todos.filter((t) => t.status === "failed");
+ if (failedChunks.length > 0) {
+ logger.info(
+ `${this.logPrefix} Resetting ${failedChunks.length} failed chunks to pending`,
+ );
+ for (const todo of failedChunks) {
+ todo.status = "pending";
+ todo.error = undefined;
+ todo.retryCount = 0;
+ }
+ await this.updateState(state);
+ }
+ }
+
+ // Phase 3: single sequential scheduler loop.
+ const active = new Map<string, T>();
+ for (const todo of stillRunning) {
+ active.set(todo.queryId!, todo);
+ logger.info(
+ `${this.logPrefix} Tracking recovered running query ${todo.queryId} for chunk ${todo.id}`,
+ );
+ }
+
+ while (!this.isAborted && !this.haltError) {
+ await this.pollActiveQueries(active, state, config);
+ if (this.isAborted || this.haltError) break;
+
+ await this.fillFreeSlots(active, state, config);
+
+ const outstanding =
+ active.size > 0 || state.todos.some((t) => t.status === "pending");
+ if (!outstanding) break;
+
+ await sleep(config.pollIntervalMs);
+ }
+
+ if (this.haltError) {
+ logger.error(this.haltError.message);
+ throw this.haltError;
+ }
+
+ if (this.isAborted) {
+ // In-flight queries keep running server-side; the next run re-attaches
+ // to them via the persisted queryIds.
+ logger.info(
+ `${this.logPrefix} Migration aborted. Can be resumed from current state.`,
+ );
+ return;
+ }
+
+ const failed = state.todos.filter((t) => t.status === "failed");
+ if (failed.length > 0) {
+ await this.onBackfillFailed(state);
+ const message =
+ `${this.logPrefix} Migration completed with ${failed.length} failed chunk(s); ` +
+ `clear failedAt and re-run with --retry-failed before downstream steps can proceed.`;
+ logger.error(message);
+ throw new Error(message);
+ }
+
+ logger.info(`${this.logPrefix} All chunks completed!`);
+ state.phase = "completed";
+ await this.updateState(state);
+
+ await this.onBackfillSucceeded(state);
+
+ logger.info(
+ `${this.logPrefix} Finished backfill in ${((Date.now() - start) / 1000 / 60).toFixed(2)} minutes`,
+ );
+ }
+
+ /**
+ * Polls every active query once and applies completions/failures to state.
+ */
+ private async pollActiveQueries(
+ active: Map<string, T>,
+ state: ChunkedBackfillState<T>,
+ config: ResolvedChunkedBackfillConfig,
+ ): Promise<void> {
+ for (const [queryId, todo] of [...active]) {
+ let status: QueryStatus;
+ try {
+ status = await pollQueryStatus(queryId);
+ } catch (error) {
+ logger.warn(
+ `${this.logPrefix} Error polling query ${queryId} for chunk ${todo.id}, will retry on next poll cycle`,
+ error,
+ );
+ continue;
+ }
+
+ if (status === "running") continue;
+
+ active.delete(queryId);
+ state.activeQueries = state.activeQueries.filter((q) => q !== queryId);
+
+ if (status === "completed") {
+ const verificationError = await this.verifyCompletedChunk(todo);
+ if (verificationError) {
+ todo.status = "failed";
+ todo.error = verificationError;
+ this.haltError = new Error(`${this.logPrefix} ${verificationError}`);
+ } else {
+ todo.status = "completed";
+ todo.completedAt = new Date().toISOString();
+ const completed = state.todos.filter(
+ (t) => t.status === "completed",
+ ).length;
+ logger.info(
+ `${this.logPrefix} Completed chunk ${todo.id} (${completed}/${state.todos.length})`,
+ );
+ }
+ } else {
+ const error =
+ status === "failed"
+ ? await getQueryError(queryId)
+ : "Query not found in query_log";
+ this.applyChunkFailure(todo, error, config);
+ }
+
+ await this.updateState(state);
+ }
+ }
+
+ /**
+ * Fires queries for pending chunks until the concurrency limit is reached.
+ */
+ private async fillFreeSlots(
+ active: Map<string, T>,
+ state: ChunkedBackfillState<T>,
+ config: ResolvedChunkedBackfillConfig,
+ ): Promise<void> {
+ while (active.size < config.concurrency) {
+ const next = state.todos.find((t) => t.status === "pending");
+ if (!next) return;
+
+ next.status = "in_progress";
+ next.queryId = generateQueryId(next.id);
+ next.startedAt = new Date().toISOString();
+ state.activeQueries.push(next.queryId);
+ // Persist before firing: a crash in between is recovered as a not_found
+ // query and the chunk falls back to pending.
+ await this.updateState(state);
+
+ try {
+ const { query, params } = this.buildChunkQuery(next);
+ await fireQuery({
+ query,
+ queryId: next.queryId,
+ params,
+ attemptNumber: next.retryCount || 0,
+ logPrefix: this.logPrefix,
+ });
+ active.set(next.queryId, next);
+ logger.info(
+ `${this.logPrefix} Started chunk ${next.id} with query ${next.queryId}`,
+ );
+ } catch (err) {
+ logger.error(
+ `${this.logPrefix} Failed to start query for chunk ${next.id}`,
+ err,
+ );
+ state.activeQueries = state.activeQueries.filter(
+ (q) => q !== next.queryId,
+ );
+ // Fire-time failures count against maxRetries too β€” a deterministic
+ // error (bad SQL, schema drift) must not retry forever.
+ this.applyChunkFailure(
+ next,
+ err instanceof Error ? err.message : String(err),
+ config,
+ );
+ await this.updateState(state);
+ return; // back off until the next poll cycle
+ }
+ }
+ }
+
+ private applyChunkFailure(
+ todo: T,
+ error: string | undefined,
+ config: ResolvedChunkedBackfillConfig,
+ ): void {
+ todo.retryCount = (todo.retryCount || 0) + 1;
+ todo.queryId = undefined;
+ if (todo.retryCount >= config.maxRetries) {
+ todo.status = "failed";
+ todo.error = error;
+ logger.error(
+ `${this.logPrefix} Chunk ${todo.id} failed permanently: ${error}`,
+ );
+ } else {
+ todo.status = "pending";
+ logger.warn(
+ `${this.logPrefix} Chunk ${todo.id} failed, will retry (${todo.retryCount}/${config.maxRetries}): ${error}`,
+ );
+ }
+ }
+
+ async abort(): Promise<void> {
+ logger.info(`${this.logPrefix} Aborting backfill migration`);
+ this.isAborted = true;
+ }
+}
+
+// ============================================================================
+// CLI entry point helper
+// ============================================================================
+
+/**
+ * Shared CLI wrapper for chunked backfill migrations. Installs the fail-fast
+ * process handlers, parses the standard flags, then validates and runs the
+ * migration. Call from the migration module's `require.main === module` block.
+ */
+export function runBackfillMigrationCli(
+ createMigration: () => IBackgroundMigration,
+ {
+ logPrefix,
+ includePartitions = true,
+ }: { logPrefix: string; includePartitions?: boolean },
+): void {
+ process.on("unhandledRejection", (reason) => {
+ logger.error(
+ `${logPrefix} Unhandled promise rejection - process will exit`,
+ {
+ reason: reason instanceof Error ? reason.message : String(reason),
+ stack: reason instanceof Error ? reason.stack : undefined,
+ },
+ );
+ process.exit(1);
+ });
+
+ process.on("uncaughtException", (error) => {
+ logger.error(`${logPrefix} Uncaught exception - process will exit`, error);
+ process.exit(1);
+ });
+
+ async function main(): Promise<void> {
+ const { values } = parseArgs({
+ options: {
+ concurrency: { type: "string", short: "c", default: "1" },
+ pollIntervalMs: { type: "string", short: "p", default: "30000" },
+ maxRetries: { type: "string", short: "r", default: "3" },
+ retryFailed: { type: "boolean", short: "f", default: false },
+ ...(includePartitions
+ ? { partitions: { type: "string", multiple: true } as const }
+ : {}),
+ },
+ }) as {
+ values: {
+ concurrency: string;
+ pollIntervalMs: string;
+ maxRetries: string;
+ retryFailed: boolean;
+ partitions?: string[];
+ };
+ };
+
+ const migration = createMigration();
+
+ const parsedArgs: ChunkedBackfillArgs = {
+ concurrency: parseInt(values.concurrency, 10),
+ pollIntervalMs: parseInt(values.pollIntervalMs, 10),
+ maxRetries: parseInt(values.maxRetries, 10),
+ retryFailed: values.retryFailed,
+ partitions: values.partitions,
+ };
+
+ const validation = await migration.validate(
+ parsedArgs as Record<string, unknown>,
+ );
+
+ if (!validation.valid) {
+ logger.error(`Validation failed: ${validation.invalidReason}`);
+ process.exit(1);
+ }
+
+ await migration.run(parsedArgs as Record<string, unknown>);
+ }
+
+ main()
+ .then(() => {
+ process.exit(0);
+ })
+ .catch((error) => {
+ logger.error(`Migration execution failed: ${error}`, error);
+ process.exit(1);
+ });
+}
diff --git a/worker/src/env.ts b/worker/src/env.ts
index c30ffc6130..acdd8543a1 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -477,6 +477,18 @@ const EnvSchema = z.object({
.enum(["true", "false"])
.default("false"),
+ // Background-migration env gates. Names share the LANGFUSE_BACKGROUND_MIGRATION_
+ // prefix so the BackgroundMigrationManager can discover them by scanning env
+ // keys; each gates one or more rows in the background_migrations table via
+ // `args.envGate`. Default to "false" so dormant migrations only run when the
+ // operator explicitly opts in.
+ LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_BACKGROUND_MIGRATION_V4_DROP_PID_TID_SORTING_TABLES: z
+ .enum(["true", "false"])
+ .default("false"),
+
LANGFUSE_EXPERIMENT_EVENT_PROPAGATION_PARTITION_DELAY_MINUTES: z.coerce
.number()
.positive()
diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
index 1af7348361..87236410ca 100644
--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts
+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
@@ -75,6 +75,15 @@ export interface SpanRecord {
trace_name: string;
user_id: string;
session_id: string;
+ /**
+ * Source row's ReplacingMergeTree version (`event_ts`, DateTime64 string).
+ * Only populated by the historic backfill (M4) fetches; the live cron leaves
+ * it undefined. Used to stamp plain (un-enriched) leftover spans with their
+ * original version so that a `now()`-stamped enriched copy of the same span β€”
+ * possibly produced by a DRI in a different batch β€” always wins the
+ * events_full merge/argMax. See `convertEnrichedSpansToEventRecords`.
+ */
+ event_ts?: string;
}
export interface EnrichedSpan extends SpanRecord {
@@ -229,7 +238,7 @@ export async function getRelevantObservations(
AND o.start_time <= {maxTime: DateTime64(3)} + interval 7 day
AND coalesce(o.environment, '') != 'langfuse-prompt-experiment'
ORDER BY o.event_ts DESC
- LIMIT 1 BY o.project_id, o.id
+ LIMIT 1 BY o.project_id, o.trace_id, o.id
`;
return queryClickhouse<SpanRecord>({
@@ -323,8 +332,37 @@ export async function getRelevantTraces(
});
}
+/**
+ * Trace-level lookup key scoped by project. Trace ids are user-supplied and
+ * only unique within a project, so the same id can exist in multiple projects
+ * within one batch; unscoped keys would let one project's data enrich
+ * another's. Use this for `(project_id, trace_id)` keys (e.g. trace
+ * properties). For span identity use `spanScopedKey`.
+ */
+export function projectScopedKey(projectId: string, id: string): string {
+ return `${projectId}:${id}`;
+}
+
+/**
+ * Span identity key, `(project_id, trace_id, span_id)`. This matches the
+ * `events_full` sort/dedup key. A span id (OTEL span id) is only unique within
+ * a trace, so two spans in different traces of the same project can share a
+ * span id; keying on `(project_id, span_id)` would collapse them or merge
+ * their children across traces.
+ */
+export function spanScopedKey(
+ projectId: string,
+ traceId: string,
+ spanId: string,
+): string {
+ return `${projectId}:${traceId}:${spanId}`;
+}
+
/**
* Build span and child maps for efficient lookups and tree traversal.
+ * Both maps are keyed by `spanScopedKey`. The child map keys a span under its
+ * parent's identity; since `parent_span_id` always references a span in the
+ * same trace, the parent shares the child's `trace_id`.
*/
export function buildSpanMaps(spans: SpanRecord[]): {
spanMap: Map<string, SpanRecord>;
@@ -334,36 +372,46 @@ export function buildSpanMaps(spans: SpanRecord[]): {
const childMap = new Map<string, SpanRecord[]>();
for (const span of spans) {
- spanMap.set(span.span_id, span);
+ spanMap.set(
+ spanScopedKey(span.project_id, span.trace_id, span.span_id),
+ span,
+ );
- // Add to parent's children list
- const parentId = span.parent_span_id;
- if (!childMap.has(parentId)) {
- childMap.set(parentId, []);
+ // Add to parent's children list. The parent lives in the same trace.
+ const parentKey = spanScopedKey(
+ span.project_id,
+ span.trace_id,
+ span.parent_span_id,
+ );
+ if (!childMap.has(parentKey)) {
+ childMap.set(parentKey, []);
}
- childMap.get(parentId)!.push(span);
+ childMap.get(parentKey)!.push(span);
}
return { spanMap, childMap };
}
/**
- * Recursively find all child spans for a given root span.
+ * Recursively find all child spans for a given root span key
+ * (see `spanScopedKey`).
*/
export function findAllChildren(
- rootSpanId: string,
+ rootSpanKey: string,
childMap: Map<string, SpanRecord[]>,
): SpanRecord[] {
const children: SpanRecord[] = [];
- const queue: string[] = [rootSpanId];
+ const queue: string[] = [rootSpanKey];
while (queue.length > 0) {
- const currentId = queue.shift()!;
- const directChildren = childMap.get(currentId) || [];
+ const currentKey = queue.shift()!;
+ const directChildren = childMap.get(currentKey) || [];
for (const child of directChildren) {
children.push(child);
- queue.push(child.span_id);
+ queue.push(
+ spanScopedKey(child.project_id, child.trace_id, child.span_id),
+ );
}
}
@@ -374,7 +422,7 @@ export function findAllChildren(
* Convert a SpanRecord to EnrichedSpan format with empty experiment fields.
* Used for spans that are not part of any dataset run item but should still be included in events.
*/
-function convertToEnrichedSpanWithoutExperiment(
+export function convertToEnrichedSpanWithoutExperiment(
span: SpanRecord,
traceProperties: TraceProperties | undefined,
): EnrichedSpan {
@@ -477,16 +525,15 @@ export function enrichSpansWithExperiment(
}
/**
- * Write enriched spans directly to the events_full table.
+ * Convert enriched spans to events_full insert records.
* Spans already have model match, usage, and cost details from ClickHouse,
- * so we skip IngestionService enrichment and write EventRecordInsertType directly.
+ * so we skip IngestionService enrichment and build EventRecordInsertType directly.
*/
-export function writeEnrichedSpans(spans: EnrichedSpan[]): void {
- if (spans.length === 0) {
- return;
- }
-
- const clickhouseWriter = ClickhouseWriter.getInstance();
+export function convertEnrichedSpansToEventRecords(
+ spans: EnrichedSpan[],
+ opts: { plainEventTsFromSource?: boolean } = {},
+): EventRecordInsertType[] {
+ const records: EventRecordInsertType[] = [];
const now = Date.now() * 1000; // microseconds
for (const span of spans) {
@@ -499,6 +546,18 @@ export function writeEnrichedSpans(spans: EnrichedSpan[]): void {
? parseInt(span.prompt_version, 10)
: undefined;
+ // Enriched spans (experiment_id set) always use now() so the most recently
+ // written experiment wins for a span shared across DRIs. Plain spans keep
+ // their source event_ts (when the caller opts in and it was fetched) so an
+ // enriched copy of the same span β€” possibly written by a later batch β€”
+ // deterministically wins the events_full merge/argMax instead of being
+ // clobbered by a now()-stamped plain duplicate.
+ const isPlain = !span.experiment_id;
+ const eventTs =
+ opts.plainEventTsFromSource && isPlain && span.event_ts
+ ? new Date(span.event_ts).getTime() * 1000
+ : now;
+
const eventRecord: EventRecordInsertType = {
id: span.span_id,
project_id: span.project_id,
@@ -584,10 +643,27 @@ export function writeEnrichedSpans(spans: EnrichedSpan[]): void {
created_at: now,
updated_at: now,
- event_ts: now,
+ event_ts: eventTs,
};
- clickhouseWriter.addToQueue(TableName.EventsFull, eventRecord);
+ records.push(eventRecord);
+ }
+
+ return records;
+}
+
+/**
+ * Write enriched spans to the events_full table via the ClickhouseWriter
+ * queue (buffered; flushed by the writer's interval).
+ */
+export function writeEnrichedSpans(spans: EnrichedSpan[]): void {
+ if (spans.length === 0) {
+ return;
+ }
+
+ const clickhouseWriter = ClickhouseWriter.getInstance();
+ for (const record of convertEnrichedSpansToEventRecords(spans)) {
+ clickhouseWriter.addToQueue(TableName.EventsFull, record);
}
logger.info(
@@ -866,19 +942,22 @@ async function processExperimentBackfill(
const allSpans = [...observations, ...traces];
const { spanMap, childMap } = buildSpanMaps(allSpans);
- // Build a map of trace_id -> {userId, sessionId} for efficient lookup
+ // Build a project-scoped map of trace properties for efficient lookup
const tracePropertiesMap = new Map<string, TraceProperties>();
for (const trace of traces) {
- tracePropertiesMap.set(trace.trace_id, {
- name: trace.name,
- userId: trace.user_id,
- sessionId: trace.session_id,
- version: trace.version,
- release: trace.release,
- tags: trace.tags,
- bookmarked: trace.bookmarked,
- public: trace.public,
- });
+ tracePropertiesMap.set(
+ projectScopedKey(trace.project_id, trace.trace_id),
+ {
+ name: trace.name,
+ userId: trace.user_id,
+ sessionId: trace.session_id,
+ version: trace.version,
+ release: trace.release,
+ tags: trace.tags,
+ bookmarked: trace.bookmarked,
+ public: trace.public,
+ },
+ );
}
// Process each dataset run item
@@ -888,7 +967,12 @@ async function processExperimentBackfill(
for (const dri of driChunk) {
// Find the root span (either observation or trace)
const rootSpanId = dri.observation_id || `t-${dri.trace_id}`;
- const rootSpan = spanMap.get(rootSpanId);
+ const rootSpanKey = spanScopedKey(
+ dri.project_id,
+ dri.trace_id,
+ rootSpanId,
+ );
+ const rootSpan = spanMap.get(rootSpanKey);
if (!rootSpan) {
logger.warn(
@@ -898,10 +982,12 @@ async function processExperimentBackfill(
}
// Get trace-level properties for this trace
- const traceProperties = tracePropertiesMap.get(dri.trace_id);
+ const traceProperties = tracePropertiesMap.get(
+ projectScopedKey(dri.project_id, dri.trace_id),
+ );
// Find all children recursively
- const childSpans = findAllChildren(rootSpanId, childMap);
+ const childSpans = findAllChildren(rootSpanKey, childMap);
// Enrich spans with experiment properties and propagate trace-level properties
const enrichedSpans = enrichSpansWithExperiment(
@@ -914,16 +1000,26 @@ async function processExperimentBackfill(
allEnrichedSpans.push(...enrichedSpans);
// Track which spans have been processed
- processedSpanIds.add(rootSpan.span_id);
+ processedSpanIds.add(
+ spanScopedKey(rootSpan.project_id, rootSpan.trace_id, rootSpan.span_id),
+ );
for (const child of childSpans) {
- processedSpanIds.add(child.span_id);
+ processedSpanIds.add(
+ spanScopedKey(child.project_id, child.trace_id, child.span_id),
+ );
}
}
// Add all remaining spans that weren't enriched (e.g., trace-derived spans that weren't roots)
for (const span of allSpans) {
- if (!processedSpanIds.has(span.span_id)) {
- const traceProperties = tracePropertiesMap.get(span.trace_id);
+ if (
+ !processedSpanIds.has(
+ spanScopedKey(span.project_id, span.trace_id, span.span_id),
+ )
+ ) {
+ const traceProperties = tracePropertiesMap.get(
+ projectScopedKey(span.project_id, span.trace_id),
+ );
allEnrichedSpans.push(
convertToEnrichedSpanWithoutExperiment(span, traceProperties),
);