Skip to content

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

chore: patch backfill for otel (#10873)

Max Deichmann547c406bc5d2
diff --git a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts
index 862b7952e6..09e8e2ca45 100644
--- a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts
+++ b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts
@@ -15,17 +15,27 @@ import * as path from "path";
import * as readline from "readline";
import { parse } from "csv-parse";
import { randomUUID } from "crypto";
-import { getQueue, QueueJobs, QueueName } from "@langfuse/shared/src/server";
+import {
+ getQueue,
+ OtelIngestionQueue,
+ QueueJobs,
+ QueueName,
+ TQueueJobTypes,
+} from "@langfuse/shared/src/server";
const INPUT_FILE = "events.csv";
const OUTPUT_FILE = "events_filtered.csv";
const JSONL_OUTPUT_FILE = "events_filtered.jsonl";
+const OTEL_JSONL_OUTPUT_FILE = "otel_events_filtered.jsonl";
// Redis configuration
// eslint-disable-next-line turbo/no-undeclared-env-vars
const QUEUE_NAME = QueueName.IngestionSecondaryQueue;
const JOB_NAME = QueueJobs.IngestionJob;
+const OTEL_NAME = QueueName.OtelIngestionQueue;
+const OTEL_JOB_NAME = QueueJobs.OtelIngestionJob;
+
interface Stats {
totalRows: number;
filteredRows: number;
@@ -48,6 +58,19 @@ interface JsonOutputItem {
};
}
+interface OTelJsonOutputItem {
+ authCheck: {
+ validKey: true;
+ scope: {
+ projectId: string;
+ accessLevel: "project";
+ };
+ };
+ data: {
+ fileKey: string;
+ };
+}
+
async function filterCsvFile(
inputPath: string,
outputPath: string,
@@ -222,13 +245,16 @@ async function filterCsvFile(
async function convertCsvToJsonl(
csvPath: string,
jsonlPath: string,
+ otelJsonlPath: string,
): Promise<void> {
console.log(`πŸ”„ Converting ${csvPath} to JSONL format...`);
console.log(`πŸ“ JSONL output will be written to ${jsonlPath}`);
+ console.log(`πŸ“ OTEL JSONL output will be written to ${otelJsonlPath}`);
const startTime = Date.now();
let processedRows = 0;
let writtenObjects = 0;
+ let writtenOtelObjects = 0;
// Check if CSV file exists
if (!fs.existsSync(csvPath)) {
@@ -238,6 +264,7 @@ async function convertCsvToJsonl(
return new Promise<void>((resolve, reject) => {
const inputStream = fs.createReadStream(csvPath);
const outputStream = fs.createWriteStream(jsonlPath);
+ const otelOutputStream = fs.createWriteStream(otelJsonlPath);
let keyColumnIndex = -1;
let headers: string[] = [];
@@ -267,6 +294,7 @@ async function convertCsvToJsonl(
parser.on("error", (err: Error) => {
clearInterval(progressInterval);
outputStream.end();
+ otelOutputStream.end();
reject(new Error(`CSV parsing error during conversion: ${err.message}`));
});
@@ -302,69 +330,114 @@ async function convertCsvToJsonl(
return;
}
- // Parse the S3 path: projectId/type/eventBodyId/eventId.json
- const pathMatch = keyValue.match(
+ // Handle two S3 key path formats:
+ // 1. projectId/type/eventBodyId/eventId.json (original)
+ // 2. otel/projectId/yyyy/mm/dd/hh/mm/eventId.json (OTEL-style)
+
+ // Match OTEL-style: otel/projectId/yyyy/mm/dd/hh/mm/eventId.json
+ const otelMatch = keyValue.match(
+ /^otel\/([^/]+)\/(\d{4})\/(\d{2})\/(\d{2})\/(\d{2})\/(\d{2})\/([^.]+)\.json$/,
+ );
+
+ // Match original format
+ const regularMatch = keyValue.match(
/^([^/]+)\/([^/]+)\/(.+)\/([^/]+)\.json$/,
);
- if (!pathMatch) {
+ if (otelMatch) {
+ const [, projectId] = otelMatch;
+ const otelJsonObject: OTelJsonOutputItem = {
+ authCheck: {
+ validKey: true,
+ scope: {
+ projectId,
+ accessLevel: "project",
+ },
+ },
+ data: {
+ fileKey: keyValue,
+ },
+ };
+
+ // Write each OTEL JSON object as a single line (JSONL format)
+ otelOutputStream.write(JSON.stringify(otelJsonObject) + "\n");
+ writtenOtelObjects++;
+ } else if (regularMatch) {
+ const [, projectId, type, eventBodyId, eventId] = regularMatch;
+
+ const jsonObject: JsonOutputItem = {
+ useS3EventStore: true,
+ authCheck: {
+ validKey: true,
+ scope: {
+ projectId,
+ accessLevel: "all",
+ },
+ },
+ data: {
+ eventBodyId,
+ fileKey: eventId,
+ type: `${type}-create`,
+ },
+ };
+
+ // Write each JSON object as a single line (JSONL format)
+ outputStream.write(JSON.stringify(jsonObject) + "\n");
+ writtenObjects++;
+ } else {
console.warn(
`⚠️ Invalid key format at row ${processedRows}: ${keyValue}, skipping...`,
);
return;
}
-
- const [, projectId, type, eventBodyId, eventId] = pathMatch;
-
- // Create JSON object with the specified structure
- const jsonObject: JsonOutputItem = {
- useS3EventStore: true,
- authCheck: {
- validKey: true,
- scope: {
- projectId,
- accessLevel: "all",
- },
- },
- data: {
- eventBodyId,
- fileKey: eventId,
- type: `${type}-create`,
- },
- };
-
- // Write each JSON object as a single line (JSONL format)
- outputStream.write(JSON.stringify(jsonObject) + "\n");
- writtenObjects++;
});
// Handle completion
parser.on("end", () => {
clearInterval(progressInterval);
outputStream.end();
+ otelOutputStream.end();
+
+ let finishedStreams = 0;
+ const checkComplete = () => {
+ finishedStreams++;
+ if (finishedStreams === 2) {
+ const processingTimeMs = Date.now() - startTime;
+ const outputFileStats = fs.statSync(jsonlPath);
+ const otelOutputFileStats = fs.statSync(otelJsonlPath);
+ const outputFileSizeGB = (outputFileStats.size / 1024 ** 3).toFixed(
+ 2,
+ );
+ const otelOutputFileSizeGB = (
+ otelOutputFileStats.size /
+ 1024 ** 3
+ ).toFixed(2);
+
+ console.log("\nπŸŽ‰ === JSONL Conversion Complete ===");
+ console.log(
+ `πŸ“Š Total rows converted: ${processedRows.toLocaleString()}`,
+ );
+ console.log(
+ `πŸ“ JSON objects written: ${writtenObjects.toLocaleString()}`,
+ );
+ console.log(
+ `πŸ“ OTEL objects written: ${writtenOtelObjects.toLocaleString()}`,
+ );
+ console.log(
+ `⏱️ Conversion time: ${(processingTimeMs / 1000).toFixed(1)} seconds`,
+ );
+ console.log(
+ `πŸš€ Average speed: ${Math.round(processedRows / (processingTimeMs / 1000)).toLocaleString()} rows/second`,
+ );
+ console.log(`πŸ“ JSONL file size: ${outputFileSizeGB} GB`);
+ console.log(`πŸ“ OTEL JSONL file size: ${otelOutputFileSizeGB} GB`);
+
+ resolve();
+ }
+ };
- outputStream.on("finish", () => {
- const processingTimeMs = Date.now() - startTime;
- const outputFileStats = fs.statSync(jsonlPath);
- const outputFileSizeGB = (outputFileStats.size / 1024 ** 3).toFixed(2);
-
- console.log("\nπŸŽ‰ === JSONL Conversion Complete ===");
- console.log(
- `πŸ“Š Total rows converted: ${processedRows.toLocaleString()}`,
- );
- console.log(
- `πŸ“ JSON objects written: ${writtenObjects.toLocaleString()}`,
- );
- console.log(
- `⏱️ Conversion time: ${(processingTimeMs / 1000).toFixed(1)} seconds`,
- );
- console.log(
- `πŸš€ Average speed: ${Math.round(processedRows / (processingTimeMs / 1000)).toLocaleString()} rows/second`,
- );
- console.log(`πŸ“ JSONL file size: ${outputFileSizeGB} GB`);
-
- resolve();
- });
+ outputStream.on("finish", checkComplete);
+ otelOutputStream.on("finish", checkComplete);
});
// Connect streams
@@ -479,16 +552,130 @@ async function processQueueBatch(
}
}
+async function ingestEventsToOtelQueue(otelJsonlPath: string): Promise<void> {
+ console.log(
+ `πŸš€ Starting to ingest OTEL events from ${otelJsonlPath} to BullMQ...`,
+ );
+
+ // Check if JSONL file exists
+ if (!fs.existsSync(otelJsonlPath)) {
+ throw new Error(`JSONL file not found: ${otelJsonlPath}`);
+ }
+
+ const startTime = Date.now();
+ let processedEvents = 0;
+
+ // Set up BullMQ queue with Redis connection
+ const queue = OtelIngestionQueue.getInstance({});
+
+ if (!queue) {
+ throw new Error("Failed to get queue");
+ }
+
+ console.log(`πŸ”— Connected to Redis and created queue: ${OTEL_NAME}`);
+
+ // Second pass: ingest events into queue in batches
+ console.log(`πŸ“₯ Starting OTEL queue ingestion...`);
+
+ const BATCH_SIZE = 1000;
+ let batch: OTelJsonOutputItem[] = [];
+ let batchNumber = 0;
+
+ const ingestStream = fs.createReadStream(otelJsonlPath);
+ const ingestRl = readline.createInterface({
+ input: ingestStream,
+ crlfDelay: Infinity,
+ });
+
+ for await (const line of ingestRl) {
+ if (!line.trim()) continue;
+
+ try {
+ const event: OTelJsonOutputItem = JSON.parse(line);
+ batch.push(event);
+
+ // Process queue ingestion in batches
+ if (batch.length >= BATCH_SIZE) {
+ batchNumber++;
+ await processOtelQueueBatch(queue, batch, batchNumber, processedEvents);
+ processedEvents += batch.length;
+ batch = [];
+ }
+ } catch {
+ // Already warned during first pass
+ }
+ }
+
+ // Process remaining batch
+ if (batch.length > 0) {
+ batchNumber++;
+ await processOtelQueueBatch(queue, batch, batchNumber, processedEvents);
+ processedEvents += batch.length;
+ }
+
+ // Close the queue connection
+ await queue.close();
+
+ const processingTimeMs = Date.now() - startTime;
+
+ console.log("\nπŸŽ‰ === OTEL Event Ingestion Complete ===");
+ console.log(`πŸ“Š Total events ingested: ${processedEvents.toLocaleString()}`);
+ console.log(
+ `⏱️ Ingestion time: ${(processingTimeMs / 1000).toFixed(1)} seconds`,
+ );
+ console.log(
+ `πŸš€ Average speed: ${Math.round(processedEvents / (processingTimeMs / 1000)).toLocaleString()} events/second`,
+ );
+ console.log(`πŸ—‚οΈ Queue name: ${OTEL_NAME}`);
+ console.log(`πŸ”§ Job name: ${OTEL_JOB_NAME}`);
+}
+
+async function processOtelQueueBatch(
+ queue: NonNullable<ReturnType<typeof getQueue>>,
+ batch: OTelJsonOutputItem[],
+ batchNumber: number,
+ processedEvents: number,
+): Promise<void> {
+ // Prepare jobs for bulk insertion
+ const jobs: Array<{
+ name: QueueJobs.OtelIngestionJob;
+ data: TQueueJobTypes[QueueName.OtelIngestionQueue];
+ }> = batch.map((event) => ({
+ name: QueueJobs.OtelIngestionJob,
+ data: {
+ payload: event,
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.OtelIngestionJob,
+ },
+ }));
+
+ // Add batch to queue
+ await queue.addBulk(jobs);
+
+ // Log progress
+ console.log(
+ `βœ… Added OTEL batch ${batchNumber} (${processedEvents + batch.length} events) to queue`,
+ );
+
+ // Log sample event from each batch for tracking
+ if (batch.length > 0) {
+ console.log(`πŸ“„ Sample OTEL event from batch: ${JSON.stringify(batch[0])}`);
+ }
+}
+
// Main execution
async function main() {
try {
const inputPath = path.resolve(INPUT_FILE);
const outputPath = path.resolve(OUTPUT_FILE);
const jsonlOutputPath = path.resolve(JSONL_OUTPUT_FILE);
+ const otelJsonlOutputPath = path.resolve(OTEL_JSONL_OUTPUT_FILE);
console.log(`πŸ“‚ Input file: ${inputPath}`);
console.log(`πŸ“‚ Output file: ${outputPath}`);
console.log(`πŸ“‚ JSONL output file: ${jsonlOutputPath}`);
+ console.log(`πŸ“‚ OTEL JSONL output file: ${otelJsonlOutputPath}`);
// Step 1: Filter the CSV file
await filterCsvFile(inputPath, outputPath);
@@ -496,13 +683,15 @@ async function main() {
console.log("\nβœ… CSV filtering completed successfully!");
// Step 2: Convert filtered CSV to JSONL
- await convertCsvToJsonl(outputPath, jsonlOutputPath);
+ await convertCsvToJsonl(outputPath, jsonlOutputPath, otelJsonlOutputPath);
console.log("\nβœ… JSONL conversion completed successfully!");
// Step 3: Ingest events to BullMQ
await ingestEventsToQueue(jsonlOutputPath);
+ await ingestEventsToOtelQueue(otelJsonlOutputPath);
+
console.log("\nβœ… Script completed successfully!");
} catch (error) {
console.error("\n❌ Error:", (error as Error).message);